python - 如何在python中获取该行以及该行之前和该行之后的数据

标签 python file

我有一个文件 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/

相关文章:

c - 为什么 fputc 不更新此代码段中的字符?

python - 在元类机制之前创建动态类字段

python - opencv 版本 3.* HogDescriptor 最多接受 1 个参数(给定 5 个)

python - 用装饰器覆盖 Django View

python - 使用 aws chalice 构建单页面应用程序?

mysql - 基于文件访问mysql数据库

python - Pandas - 比较 2 个数据帧以查找每天的第一个实例,其中值是第一个数据帧的倍数

apache - Apache 可以处理 URL 中的 +(加号)空格吗?

java - 动态查找文件

c# - 如何在 C# 中创建 CSV 文件