问题描述
我创建了此脚本来读取.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
解决方法
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)