我有一个文件 example.txt,其中包含以下数据 example.txt:
Email & Password: hifza
name: abc
Country: US
Email & Password: trfff
name: abc
Country: US
Email & Password: trfff
name: xyz
Country: US
Email & Password: trfff
name: ttt
Country: US
我想将数据存储在三个不同的文件中。如果名称是 abc 电子邮件,名称和国家应存储在 abc.txt 文件中。如果名称是 xyz,则 xyz 的所有数据应放在 xyz.txt 中。 这是我的代码,它只保存名称行的数据。但我也想要电子邮件和国家。
with open("example.txt") as f:
with open("abc.txt", "w") as f1:
for line in f:
if "abc" in line:
f1.write(line)
elif "xyz" in line:
with open("xyz.txt", "w") as f2:
f2.write(line)
elif "ttt" in line:
with open("ttt.txt", "w") as f3:
f3.write(line)
最佳答案
这应该可以解决问题:
with open("test.txt", "r") as infile:
line = infile.read().split("\n\n")
for l in line:
l = l.strip() // get rid spaces and empty lines
l = l.split("\n")
filename = l[1].split(":")[1].strip() + ".txt"
with open(filename, "w+") as outfile:
for i in l:
outfile.write(i + "\n")
关于python - 如何在python中获取该行以及该行之前和该行之后的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923755/