简体   繁体   English

使用 python 将多个 txt 文件合并到 csv

[英]Merging multiple txt files into csv with python

*very new to Python I need to merge a large number of txt files from a single directory into one csv file. *对 Python 非常陌生,我需要将单个目录中的大量 txt 文件合并到一个 csv 文件中。 The text from the files needs to be converted into separate rows and columns (five columns in each file, N number of rows).文件中的文本需要转换成单独的行和列(每个文件五列,N 行)。 I used the code from this question :我使用了这个问题的代码:

import os
import csv

dirpath = 'path_of_directory'
output = 'output_file.csv'
with open(output, 'w') as outfile:
    csvout = csv.writer(outfile)
    csvout.writerow(['FileName', 'Content'])

    files = os.listdir(dirpath)

    for filename in files:
        with open(dirpath + '/' + filename) as afile:
            csvout.writerow([filename, afile.read()])
            afile.close()

    outfile.close()

It works for me but it puts all the content from the file into one table cell.它对我有用,但它将文件中的所有内容放入一个表格单元格中。 I read through a lot of Q&As and couldn't figure out how to modify the code in order to separate the content into different columns and rows.我阅读了很多问答,无法弄清楚如何修改代码以将内容分成不同的列和行。

You have to read the five words in a line with loop for all the lines.您必须阅读所有行的循环中的五个单词。 Next, write the five words along the filename as shown below.接下来,沿着文件名写下五个单词,如下所示。 Hope that helps.希望有帮助。 I have added pseudo code for the concept.我为这个概念添加了伪代码。 Hope that helps!!!希望有帮助!!!

files = os.listdir(dirpath)

for filename in files:
    with open(dirpath + '/' + filename) as afile:
        #for line in afile.read()
        #     words_in_a_line = split_line_to_get_words(line) 
        #     csvout.writerow([filename, words_in_a_file])

        csvout.writerow([filename, afile.read()]) # delete this line
        afile.close()

outfile.close()

Here the function split_line_to_get_words will return a list of five words from the line.此处 function split_line_to_get_words 将返回该行中五个单词的列表。 If the lines are separated according to space or comma, use them to get five words from a line.如果根据空格或逗号分隔行,则使用它们从一行中获取五个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM