python - 在python中修改txt文件
问题描述
我的文件 .txt 格式如下:
Address Name
0x0802da50 xxx
0x0802da50 xxx
我想只列出地址列并将其写入另一个 txt 文件(前面的空格也是不必要的)。这是我写的:
def print_address():
input_file = 'Address&Name.txt'
destination_file = 'Address.txt'
with open(destination_file, 'a') as f1:
with open(input_file, 'r') as f2:
for num, line in enumerate(f2.readlines(), 1):
for word in input_file:
if word.startswith("0x"):
f1.write(f'{word}')
print_address()
不过,我得到的是空文件,而不是:
Address
0x0..
0x0..
解决方案
有很多方法可以实现 tis,但是使用您定义的结构,您可以执行以下操作:
input_file = 'a.txt'
destination_file = 'b.txt'
with open(input_file, 'r') as f2:
with open(destination_file, 'a') as f1:
contents=f2.readlines()
for line in contents:
word = line.split(" ")[0]
if word.startswith("0x"):
f1.write(f'{word}\n')
编辑:所以,正如评论所指出的,虽然我想在我之前的回答中保留你的结构,但这可以优化。例子 :
input_file = 'a.txt'
destination_file = 'b.txt'
with open(input_file, 'r') as f2, open(destination_file, 'a') as f1:
for line in f2.readlines():
f1.write(f'{line.split()[0]}\n')
会做同样的工作。
推荐阅读
- python - Flask 禁用 JSON 响应转义
- python - 如何在特定行上旋转熊猫数据框
- apache-kafka - Kafka Mirror Maker:同步 __consumer_offsets 主题重复项
- php - 如何在三个表上运行两个查询并在一个表中输出一列的结果
- python - 我的列表正在更改,我不知道为什么
- java - 向 arrayList 添加标记会导致应用程序崩溃
- python - 如何在python中概率性地填充列表?
- twitter-bootstrap - 无法在引导卡中添加两列
- python - 在 sympy 中生成一个多变量多项式
- reactjs - 用 redux 命名导出?