我正在尝试从一个文件中获取数据并创建两个写入新文件的列表。其中一个列表包含6个字符或更少的字符,第二个列表包含一个名称不包含" a"或者" e。"我已经完成了将形成两个列表的代码,我已经分别尝试了它们并且它们可以工作但是,我不能让它们同时附加到新列表。我首先执行的列表将是唯一一个附加到新文件的列表。任何帮助将不胜感激!
main_file = open("words.txt", "r")
#loops to find lists
lists = open('test.txt')
lists.read()
with open("test.txt", "a") as lists:
for names in main_file:
if len(names) <= 6:
lists.write(names)
line = True
for line in main_file:
if "a" in line or "e" in line or "A" in line:
line = False
else:
lists.write(line)
答案 0 :(得分:0)
如果我理解你的qn正确
import re
l1 = []
l2 = []
lists = open('test.txt','w')
with open('words.txt') as f:
for line in f.read().split('\n'):
if len(line) <= 6:
l1.append(line)
if not re.search(r'a|e', line):
l2.append(line)
lists.write('\n'.join( l1+l2 ) )
lists.close()