![](/img/trans.png)
[英]How to extract separate nth lines from a txt file and assign them to key:value pairs in python 3?
[英]How do I extract a bunch of lines from one .txt file and add them to another?
https://repl.it/join/zlkssoum-muhammadqadeer
file = open("Teacher Database.txt", "r")
lines = file.readlines()
for i in range(15, 28):
KM = open("Karen McAskill.txt", "a")
KM.write(lines[i])
KM.close()
我有一个主数据库文件,但我想从该主文件中获取信息并将其添加到 5 个单独的较小文件中。 我尝试过使用 for 循环,但每次运行程序时,信息都会复制到较小的文件中。 我想获取信息并将其写入较小的文件一次。
从原始文件中读取所有行后,您可以再次以写入模式打开它,然后将要保留的行写回原文件,然后将 rest 写入另一个文件。
file = open("Teacher Database.txt", "r")
lines = file.readlines()
file = open("Teacher Database.txt", "w")
KM = open("Karen McAskill.txt", "a")
for i in range(len(lines)):
if i >= 25 and i <= 28:
# the lines you want to move
KM.write(lines[i])
else:
# the lines you want to keep
file.write(lines[i)
KM.close()
file.close()
您可以添加更多分支逻辑以移动到其他文件。
您可以拆分文件数据,然后将数据写入文件,而不是使用行号。 此代码将自动使用人名创建文件。
with open("Teacher Database.txt") as fp:
for person in fp.read().split('Name: '):
if person.strip():
file_name = person.split('\n', 1)[0] + '.txt'
with open(file_name, 'a') as fw:
fw.write('Name: ' + person)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.