如何从.txt文件读取某些字符并将其写入Python中的.csv文件?

时间:2020-06-11 16:21:32

标签: python csv write

因此,我目前正在尝试使用Python从.txt文件中创建整洁的.csv文件。第一步是将一些8位数字放入称为“ Number”的列中。我已经创建了标题,只需要将每行中的每个数字放入列中。我想知道的是,如何告诉Python读取.txt文件中每行的前八个字符(与我要查找的数字相对应),然后将它们写入.csv文件?这可能很简单,但我只是Python的新手!

到目前为止,我有这样的东西:

with open(r'C:/Users/test1.txt') as rf:
    with open(r'C:/Users/test2.csv','w',newline='') as wf:
        outputDictWriter = csv.DictWriter(wf,['Number'])
        outputDictWriter.writeheader()
        writeLine = rf.read(8)
        for line in rf:
            wf.write(writeLine)

3 个答案:

答案 0 :(得分:0)

您可以使用pandas

import pandas as pd

df = pd.read_csv(r'C:/Users/test2.txt')
df.to_csv(r'C:/Users/test2.csv')

以下是读取文件中每行的前8个字符并将其存储在列表中的方法:

with open('file.txt','r') as f:
    lines = [line[:8] for line in f.readlines()]

答案 1 :(得分:0)

您可以使用正则表达式与字符一起选择数字。搜索它 模式= re.searh(w * \ d {8})

答案 2 :(得分:0)

只需退后一步,然后再次阅读您需要的内容:

读取.txt文件中每行的前八个字符(与我要查找的数字相对应),然后将它们写入.csv文件

现在忘了Python并用伪代码解释要做什么:

open txt file for reading
open csv file for writing (beware end of line is expected to be \r\n for a CSV file)
write the header to the csv file
loop reading the txt file 1 line at a time until end of file
    extract 8 first characters from  the line
    write them to the csv file, ended with a \r\n
close both files

好,是时候将上述伪代码转换为Python语言了:

with open('C:/Users/test1.txt') as rf, open('C:/Users/test2.csv', 'w', newline='\r\n') as wf:
    print('Number', file=wf)
    for line in rf:
        print(line.rstrip()[:8], file=wf)
相关问题