【问题标题】:Several text files to csv with filename带有文件名的几个文本文件到 csv
【发布时间】:2021-09-22 21:30:21
【问题描述】:

我在一个文件夹中有几个文本文件,我想将它们转换为 csv。在每一行中,我想在一列中包含我的文件名,在另一列中包含内容,例如:

file1.txt,该文件中包含的所有文本

file2.txt,这里有更多文字

...

我正在使用以下代码:

from glob import glob
import pandas as pd
files=os.listdir("where the text files are saved")
content=[]
for file in files: 
    with open(file, 'r', newline='') as source_file: 
        for line in csv.reader(source_file): 
            content.append(line[0]) 
with open('output.csv', 'w') as target_file: 
    for line in content: 
        target_file.write(out_filename + "," + line + '\n')

但是,使用此代码,我只能在 csv 中获取文本文件的内容。谁能解释我如何在列中添加文件名?

【问题讨论】:

    标签: python csv filenames txt


    【解决方案1】:
    import csv
    import pandas as pd
    filelocation = "FILELOCATION"
    files= [k for k in next(os.walk(f"{filelocation}"))][2]
    filenames = []
    content=[]
    for file in files:
        with open(f"{filelocation}\\{file}", 'r', newline='') as source_file:
            filenames.append(file)
            lines = source_file.read()
            content.append(lines)
    
    data = {'Filename':filenames,
            'Content':content}
    
    df = pd.DataFrame(data)
    print (df)
    
    df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv', index = False)
    

    【讨论】:

    • 您可能更喜欢os.path.join 而不是f"{filelocation}\\{file}"
    • 谢谢。该代码允许我按照我的需要获得一个带有文件名的列和另一个带有内容的列。但是我的文字是法语的,所以出于某种原因,“élections”之类的词被“élections”或“françois”替换为“françois”。有没有办法避免这种情况?以前的代码没有发生这种情况。
    • 不确定语言。但是,如果可行,您可以重用和合并您使用的代码。只需将您的 line[0] 附加到列表中即可。在遍历该文件的循环末尾的每一行之后,将该列表附加到内容
    • 正如我所说,我不确定语言,它可能是 pandas 实现,在这种情况下,读取文件的任何一种方式都行不通。那么这将是一个以不同方式写入 csv 的问题
    • 抱歉,回答迟了。在我看来,问题出在熊猫身上。也许如果我使用: with open('output.csv', 'w') as out_file,我不会收到这些错误。但我不知道如何完成这段代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2012-11-04
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多