我正在尝试读取.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)发布于 2019-06-14 05:37:58
因为你知道你每次要读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
0008https://stackoverflow.com/questions/56588640
复制相似问题