[英]Running python code on multiple files in folder and writing them to separate files
我正在研究在文件夾中的多個文件上運行腳本的代碼。 我可以在每個文件上運行代碼,但是它僅保存到一個輸出文件,然后重寫該文件。 如何獲得此代碼以將輸出保存到單獨的文件? 最好使用與每個原始文件相似的名稱。 到目前為止,這就是我所擁有的。
import os, re
import pandas as pd
directory = os.listdir('C:/Users/user/Desktop/NOV')
os.chdir('C:/Users/user/Desktop/NOV')
for file in directory:
df = pd.read_csv(file, index_col="DateTime", parse_dates=True)
df = df.resample('1min').mean()
df = df.reindex(pd.date_range(df.index.min(), df.index.max(), freq="1min"))
df.to_csv("newfile.csv", na_rep='NaN')
只需在循環的每次迭代的最后一行更改文件名。 類似於for i, file in enumerate(directory):
然后df.to_csv("new_" + file + ".csv", na_rep='NaN')
將df.to_csv("new_" + file + ".csv", na_rep='NaN')
。
好吧,很顯然它將始終寫入同一文件,因為您總是在to_csv
提供相同的文件名。 使用os.path.basename
基於舊文件名創建一個新文件名,不帶擴展名:
df.to_csv(os.path.basename(file) + "-processed.csv", na_rep='NaN')
我的方法:
glob.glob
而不是os.listdir
過濾掉不是csv
文件的文件 os.chdir
,這是一種不好的做法,因為其他模塊可能不知道您更改了當前目錄,並且兩次更改了dir都會導致相對失敗,因此使用glob.glob
可以避免這種情況。 "new_"
的文件(運行兩次將創建"new_new_
文件"new_new_
) 碼:
import os, re, glob
import pandas as pd
input_dir = 'C:/Users/user/Desktop/NOV'
for file in glob.glob(os.path.join(input_dir,"*.csv")):
df = pd.read_csv(file, index_col="DateTime", parse_dates=True)
df = df.resample('1min').mean()
df = df.reindex(pd.date_range(df.index.min(), df.index.max(), freq="1min"))
new_filename = os.path.join(input_dir,"new_"+os.path_basename(file))
df.to_csv(new_filename, na_rep='NaN')
您在for循環中引用的“文件”應該是您在目錄中操作的文件的字符串。
for file in directory:
print file
#oldfile.csv
您可以使用它來創建一個參考原始文件的新文件。 像這樣:
for file in directory:
df.to_csv("Output -" + file, na_rep='NaN') #make this the last line of your for-loop.
#File will be called 'Output - oldfile.csv'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.