簡體   English   中英

Python:將多個 .log 文件轉換為 .csv

[英]Python: Converting multiple .log files to .csv

我有 174 個.log文件需要轉換為.csv 我是 Python 的中級初學者,但想創建一些代碼來循環而不是手動執行。 所有輸入文件都在一個文件夾中。

我使用了來自課程和其他論壇的一些指針,下面的代碼在輸出文件夾中創建了文件,但它們是空的。 我想知道問題是否是由於同時使用'open'讀/寫和 Pandas csv_read/df.to_csv的?

我錯過了什么還是這里有錯誤? 我將不勝感激任何幫助和指示! 我已經盯着它看了好幾天了。

正如我所說,我是一個初學者,只想通過學習 Python 使生活更輕松:)

directory = input("Input folder:")
output = input("Output folder:")
txt_files = os.path.join(directory, '*.log')

for txt_file in glob.glob(txt_files):
    with open(txt_file, "rb") as input_file:
        in_txt = pd.read_csv(input_file, names=['Subject','Trial','Event Type','Code','Time','TTime','Uncertainty','Duration','Uncertainty_1','ReqTime','ReqDur','Stim Type','Pair Index'], skiprows=1, delimiter='\t')
        df = pd.DataFrame(in_txt,columns=['Subject','Trial','Event Type','Code','Time','TTime','Uncertainty','Duration','Uncertainty_1','ReqTime','ReqDur','Stim Type','Pair Index'])
        filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'

        with open(os.path.join(output, filename), 'wb') as output_file:
            df.to_csv(filename, index=False)

嘗試這個:

directory = input("Input folder:")
output = input("Output folder:")
txt_files = os.path.join(directory, '*.log')

for txt_file in glob.glob(txt_files):

    in_txt = pd.read_csv(input_file, names=['Subject','Trial','Event Type','Code','Time','TTime','Uncertainty','Duration','Uncertainty_1','ReqTime','ReqDur','Stim Type','Pair Index'], skiprows=1, delimiter='\t')
    df = pd.DataFrame(in_txt,columns=['Subject','Trial','Event Type','Code','Time','TTime','Uncertainty','Duration','Uncertainty_1','ReqTime','ReqDur','Stim Type','Pair Index'])
    filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'

    filename = os.path.join(output, filename)

    df.to_csv(filename, index=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM