我試圖將一個.xlsx檔案轉換為.csv檔案,只要有一個新檔案被添加到Inputfolder中,并將轉換后的.csv檔案放到OutputFolder中。
import glob
import time
import os
import pandas as pd
#Get timestamp"%Y%m%d_%H%M%S"/span>)
#輸入檔案路徑
input_filepath = 'C:/Documents/InputFile'。
folderSize = 0
#轉換檔案的函式
def format_csv(latest_file)。
#Output file path:
filenamepath = 'C:/Documents/OutputFile/' timestr ' .csv'.
read_Excelfile = pd.read_excel(latest_file)
read_Excelfile.to_csv(filenamepath, index=None, header=True)
while True:
checkFolder = folderSize
folderSize = 0: checkFolder = folderSize
#檢查輸入檔案夾的大小。
for path, dirs, files in os.walk(input_filepath) 。
for f in files:
fp = os.path.join(path, f)
folderSize = os.path.getsize(fp)
print(folderSize)
#Create new .csv file if the Input folder has new file added[/span]。
if(folderSize > checkFolder)。
list_of_files = glob.glob('C:/Documents/InputFile/*.xlsx')
latest_file = max(list_of_files, key=os.path.getctime)
format_csv(latest_file)
print(update_file)
time.sleep(15)
現在,程式只轉換第一個.xlsx檔案。如果我在InputFolder中添加一個新的.xlsx檔案,該檔案不會被轉換。
uj5u.com熱心網友回復:
你可以嘗試在檔案夾中讀取所有的.xlsx檔案,如果它找到一個檔案,就把它轉換為.csv
。在這里,我們正在讀取所有xlsx檔案的目錄,通過創建csv版本的副本來轉換它們,然后洗掉原始xlsx版本
。import pandas as pd
import os
path = 'C:/Documents/InputFile'/span>
files = os.listdir(path)
for file in files。
if '.xlsx' in file:
filename = file[:-5]
new_filename = path "/" filename " .csv"]
if filename ".csv" in files。
pass in files.
else:
df = pd.read_excel(file)
df.to_csv(new_filename)
uj5u.com熱心網友回復:
我已經即興創作了我的原始代碼。所以,每當我把一個新的excel檔案放到InputFolder中,程式就會把該檔案轉換成.csv格式,并把格式化的檔案插入OutputFolder中
import glob
import time
import os
import pandas as pd
from watchdog.observer import Observer
from 看門狗.事件 import FileSystemEventHandler
#Function if new file is created in the folder
def on_created(event)。
list_of_files = glob.glob('C:/Users/Documents/InputFolder/*.xlsx'/span>)
latest_file = max(list_of_files, key=os.path.getctime)
format_csv(latest_file)
#Function to convert .xlsx to .csv.
def format_csv(latest_file)。
# Get timestamp:latest_file.
timestr = time.strftime("%d%m%Y_%H%M%S"/span>)
#輸出檔案路徑
filenamepath = 'C:/Users/Documents/OutputFolder/' timestr ' .csv'
read_Excelfile = pd.read_excel(latest_file)
read_Excelfile.to_csv(filenamepath, index=None, header=True)
print(filenamepath)
if __name__ == "__main__"/span>:
event_handler = FileSystemEventHandler()
#Calling function for file insertion。
event_handler.on_created = on_created
#Input Folder[/span]。
path = 'C:/Users/Documents/InputFolder'/span>
#Function to observe file[/span]。
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try。
#Check every one second。
while True:
time.sleep(1)
except KeyboardInterrupt:
#如果鍵盤中斷,程式停止。
observer.stop()
observer.join()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332753.html
標籤:
