【问题标题】:How can I extract lines of data based on different categories in one column into separate text files?如何将一列中基于不同类别的数据行提取到单独的文本文件中?
【发布时间】:2021-01-27 07:55:02
【问题描述】:

我创建了这个脚本来读取一个 .txt 文件,然后根据一个特定的词引擎将它分成两个 .txt 文件。如何根据第二列将行提取到不同的文件?例如,我希望将下面的 file.txt 分成 7 个不同的文件。

file = open("file_base.txt", 'r')
lines = file.readlines()
file.close()

file1 = open("file_1.txt", 'w')
file2 = open("file_2.txt", 'w')

for line in lines:
    if 'engine' in line:
        file2.write(line)
    else:
        file1.write(line)

print("All lines that contain engine have been removed from first file")
print("All lines that contain engine has been added to second file")

file.close()
file1.close()

file_base.text

Honda,engine
Honda,cooling+system
Honda,heat+&+air+conditioning
Honda,fuel+&+air
Honda,brake+&+wheel+hub
Honda,wiper+&+washer
Honda,electrical
Toyota,engine
Toyota,cooling+system
Toyota,heat+&+air+conditioning
Toyota,fuel+&+air
Toyota,brake+&+wheel+hub
Toyota,wiper+&+washer
Toyota,electrical
Ford,engine
Ford,cooling+system
Ford,heat+&+air+conditioning
Ford,fuel+&+air
Ford,brake+&+wheel+hub
Ford,wiper+&+washer
Ford,electrical
Chevrolet,engine
Chevrolet,cooling+system
Chevrolet,heat+&+air+conditioning
Chevrolet,fuel+&+air
Chevrolet,brake+&+wheel+hub
Chevrolet,wiper+&+washer
Chevrolet,electrical

【问题讨论】:

    标签: python python-3.x file extract data-extraction


    【解决方案1】:
    with open("file_base.txt", 'r') as file:
       for line in file:
          parts = line.strip().split(',')
          with open(f"{parts[1]}.txt", 'a') as file2:
             file2.write(line)
    

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多