使用Python的文本文件数据,分类和使其他文本文件
问题描述:
使用python,我想分离一些数据文件。 文件格式是文本文件,并且没有选项卡内部数据之间只有一个空格。使用Python的文本文件数据,分类和使其他文本文件
这里是示例文件,
//test.txt
Class name age room fund.
13 A 25 B101 300
12 B 21 B102 200
9 C 22 B103 200
13 D 25 B102 100
20 E 23 B105 100
13 F 25 B103 300
11 G 25 B104 100
13 H 22 B101 300
我要带只包含行具体的数据,
类:13,基金300
,并保存另一个文本文件。
如果此代码的工作,使文本文件是
//new_test.txt
Class name age room fund.
13 A 25 B101 300
13 F 25 B103 300
13 H 22 B101 300
感谢。 HK
答
这应该做。
with open('new_test.txt','w') as new_file:
with open('test.txt') as file:
print(file.readline(),end='',file=new_file)
for line in file:
arr=line.strip().split()
if arr[0]=='13' and arr[-1]=='300':
print(line,end='',file=new_file)
但是,您应该在提问时包含您的代码。它确保提供此网站的目的。
答
如果要筛选数据:
def filter_data(src_file, dest_file, filters):
data = []
with open(src_file) as read_file:
header = [h.lower().strip('.') for h in read_file.readline().split()]
for line in read_file:
values = line.split()
row = dict(zip(header, values))
data.append(row)
for k, v in filters.items():
if data and row.get(k, None) != v:
data.pop()
break
with open(dest_file, 'w') as write_file:
write_file.write(' '.join(header) + '\n')
for row in data:
write_file.write(' '.join(row.values()) + '\n')
my_filters = {
"class": "13",
"fund": "300"
}
filter_data(src_file='test.txt', dest_file='new_test.txt', filters=my_filters)
我很抱歉,我忘了附上我的代码。感谢您的指出。 –