我正在将文本文档导入列表,然后删除任何以大写字母开头的项目。我可以运行代码,但输出文件中没有任何内容。
相关守则:
def filtercaps(infilename,outfilename):
import csv
list_of_words=[]
list=[]
a=0
with open(infilename, newline='') as inputfile:
for row in csv.reader(inputfile):
list.append(row)
for i in range(len(list)):
c=str(list[i])
if c[0] in 'qwertyuiopasdfghjklzxcvbnm':
list_of_words[a]=list[i]
a=a+1
f = open(outfilename)
for i in range(len(list_of_words)):
f.write(list_of_words[i])
f.close()
filtercaps("Enable1.txt","Enable2.txt")
答案 0 :(得分:0)
从代码中可以看出,您的文件实际上是一个csv文件(您正在使用csv.reader
读取该文件)。假设是这种情况,以下情况应该有效:
def filtercaps(infilename,outfilename):
import csv
list_of_words=[]
list=[]
with open(infilename) as inputfile:
for row in csv.reader(inputfile):
list.append(row)
for l in list:
if len(l) == 0:
continue
first_entry = l[0]
first_letter = first_entry[0][0]
if first_letter in 'qwertyuiopasdfghjklzxcvbnm':
list_of_words.append(l)
f = open(outfilename, "w")
writer = csv.writer(f)
for l in list_of_words:
writer.writerow(l)
f.close()
filtercaps("Enable1.txt","Enable2.txt")
还有其他一些方法可以让脚本更加惯用于python。