1

所以我目前正在尝试使用 Python 从 .txt 文件创建一个整洁的 .csv 文件。第一阶段是将一些 8 位数字放入一个称为“数字”的列中。我已经创建了标题,只需将每行中的每个数字放入列中。我想知道的是,如何告诉 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)
4

3 回答 3

0

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

于 2020-06-15T14:06:41.413 回答
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)
于 2020-06-15T14:07:17.297 回答
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()]
于 2020-06-11T16:26:06.890 回答