python - 读入文件中一行的前 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)
解决方案
由于您知道每次都想读取 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
推荐阅读
- python - Candlestick Charts with Matplotlib v2.2.2?
- javascript - 自定义数组到自定义对象?
- python - Scrapy error pulling up Selector
- elasticsearch - ElaticSearch 在删除空格和空格字符后查找所有重复项
- vim - 是否可以在 vim 中更改每个文件类型的选项卡标题颜色?
- scala - Spark Listener 中使用的累加器导致值不准确
- mysql - 在 Raspberry 上使用 CRON 备份数据库
- ruby - 在 ruby 中编写类的 attr_accesor 方法
- ios - 如何在 Delphi 中使用 Safari View Controller API 打开 url?
- teradata - 对 TIMESTAMP 值执行 if/else 时出现不匹配错误