首页 > 解决方案 > 读入文件中一行的前 4 位并存储

问题描述

我正在尝试读取.dat文件中的前 4 位数字并将其存储在每一行的循环中。该.dat文件如下所示:

0004 | IP
0006 | IP
0008 | IP

我想创建一个读取前四位数字并存储的循环,用于循环的迭代,直到它读取整个文件,然后将其写入输出文件。

我写了这个,但它所做的基本上是将 .dat 转换为 csv

with open('stores.dat', 'r') as input_file:
    lines = input_file.readlines()
    newLines = []
    for line in lines:
        newLine = line.strip('|').split()
        newLines.append(newLine)


with open('file.csv', 'w') as output_file:
    file_writer = csv.writer(output_file)
    file_writer.writerows(newLines)

标签: pythoncsv

解决方案


由于您知道每次都想读取 4 个字符,因此您可以只读取一个片段:

import csv

# you can open multiple file handles at the same time
with open('stores.dat', 'r') as input_file, \
     open('file.csv', 'w') as output_file:
    file_writer = csv.writer(output_file)
    # iterate over the file handle directly to get the lines
    for line in input_file:
        row = line[:4] # slice the first 4 chars
        # make sure this is wrapped as a list otherwise
        # you'll get unsightly commas in your rows
        file_writer.writerow([row])

哪个输出

$ cat file.csv
0004
0006
0008

推荐阅读