首页 > 解决方案 > 在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..

标签: python

解决方案


有很多方法可以实现 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')

会做同样的工作。


推荐阅读