如何读取txt文件的一个分支并用python写入一个新的txt文件?

how to read a branch of txt files and write in a new txt file with python?

我在“\data”中有一些 txt 文件,例如“1.txt”和“2.txt”。现在我想将这两个文件的最后一行添加到另一个名为“3.txt”的文件中,但我只能将“1.txt”的最后一行添加到“[=16=” ]'

from sys import argv

from os.path import exists

script,from_file,to_file=argv

in_file=open(from_file) in_data=in_file.readlines() count=len(in_data)

#print in_data[3] print count line=in_data[count-1]

in_file.close()

out_file=open(to_file,'w')
out_file.write(line)

out_file.close()
in_file.close()

您正在使用 'w' 打开输出文件,这意味着 'write',因此它将覆盖任何现有内容(而不是 'a' - 追加)。
因此,假设您在 \data 文件夹中的每个文件上多次 运行 脚本,您只是一遍又一遍地覆盖该文件,这就是为什么最后只得到一行的原因。

正如 yozziz74 提到的,您正在以写入模式打开文件,因此每次都会覆盖,但您还没有定义要写入文件的行变量。如果所需的效果是覆盖每个,则保留 'w' 否则更改为 'a'.

这段代码应该可以满足您的需求:

from os import listdir
from sys import argv
from os.path import exists

files = [ file for file in listdir('.') if file.endswith('.txt') ]

to_file=argv[1]

out_file=open(to_file,'a')

for file in files:
    in_file=open(file)
    lines=in_file.readlines()

    last_line=lines[-1]
    in_file.close()

    out_file.write(last_line)
    in_file.close()

out_file.close()