如何将一列中基于不同类别的数据行提取到单独的文本文件中?
How can I extract lines of data based on different categories in one column into separate text files?
我创建这个脚本是为了读入一个 .txt 文件,并根据特定的词 engine 将它分成两个 .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)
我创建这个脚本是为了读入一个 .txt 文件,并根据特定的词 engine 将它分成两个 .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)