【发布时间】:2020-06-28 16:47:00
【问题描述】:
我正在编写此函数以从文件中读取并写入另一个输出文件,但我没有收到任何输出。我是否正确编写了这些函数?如果它们是正确的,则问题出在解码函数的主体中,我将尝试解决。
代码:
def ReadFile(): #Reads data from file
try:
count=0
stringvar=INFILE.open("K:\Data.txt","r")
for line in INFILE:
mylist.append(line.rstrip())
count+=1
INFILE.close()
return count
except:
print("File could not be found")
exit()
编写输出文件代码:
def WriteFile(outlist): #outputs data to output list
OUTFILE=open("Output.txt","a")
for details in outlist:
OUTFILE.write(details+"/n")
parselist.append(a+": Was issued by " +b+ " in "+c+".""The card expires on "+d1+"/"+d2+".The card i linked to" +e+ "with account number:" +f)
OUTFILE.close()
上面的代码有问题吗?
如果有帮助,我会发布我编写的整个代码。
【问题讨论】:
-
这能回答你的问题吗? How to read a file line-by-line into a list?
-
你有没有试过在文件读取之后打印
mylist的内容,在文件写入之前打印outlist的内容?查看文件是否被实际读取以及解码是否正确完成可能会有所帮助。 -
不确定你为什么有
INFILE.open?它应该只是open(your_file, "r")。 -
我会尽快尝试
-
btw:最好使用 with 语句,例如:
with open(<file>, <mode>, ...) as opened_file: <do your stuff here>。因此,您可以在块内定义需要完成的操作,而无需在最后关闭文件。一切都由幕后使用的上下文管理器为您完成。