我有一个名为" file.txt"的文件。我想编写程序的第一部分,以便首先输出2个文件。 我的代码:
f = open("file.txt", "r+")
def Filter_NoD(f):
"""this function filters out lines with no D region and saves them in a separate file"""
lines = open(f, "r+").read().splitlines()
NoD = open("NoD.txt", "w")
withD = open("withD.txt", "w")
for i, line in enumerate(lines):
if ">No D" in line:
NoD.write(lines[i-2]+"\n"+lines[i-1]+"\n"+lines[i])
else:
withD.write(line+"\n")
return NoD, withD
我无法输出2个文件,NoD.txt和withD.txt,我也尝试了退出语句,但仍然没有输出文件。 我做错了什么?
答案 0 :(得分:1)
你永远不会调用实际的功能。
答案 1 :(得分:1)
首先,你的缩进是错误的。
其次,您将f
传递给def
,但似乎f
是文件处理程序,因此您无法在定义中再次打开它。
这是一个有效的代码:
file.txt
的内容:
asd
>No D bsd
csd
代码:
f = open("file.txt", "r+")
def Filter_NoD(f):
"""this function filters out lines with no D region and saves them in a separate file"""
lines = f.read().splitlines() # As f is already a file handler, you can't open it again
NoD = open("NoD.txt", "w")
withD = open("withD.txt", "w")
for i, line in enumerate(lines):
if ">No D" in line:
NoD.write(lines[i-2]+"\n"+lines[i-1]+"\n"+lines[i])
else:
withD.write(line+"\n")
return NoD, withD
Filter_NoD(f) # Dont forget to call the function, and that you pass a file handler in
运行NoD.txt
的内容:
csd
asd
>No D bsd
withD.txt
的内容:
asd
csd
答案 2 :(得分:1)
当我复制并粘贴你上面的函数Filter_NoD
并在某个文件上调用它时,我写了一些名为file.txt
的乱码:
some
stuff
inasd
this
file
>No D
sthaklsldf
我得到两个包含预期输出的文件输出NoD.txt
和withD.txt
。这证实了我怀疑你的代码大多是正确的。
所以,我猜想有几件事情会发生:
您没有查看正在调用python程序的正确文件夹,因此文件正在保存,而不是您正在查找的位置。
您是否从python解释器中收到任何错误?我问,因为在您提供的代码段中,f = open("file.txt", "r+")
位于Filter_NoD
的函数定义之上。您是使用文件对象(Filter_NoD
)而不是f
期望的文件路径调用Filter_NoD
吗?如果是这样,那么程序会出错并且不会被写入。
除了上述内容之外,您还需要小心打开文件对象的方式。在with
块中对打开的文件进行定位更加安全,例如:
def Filter_NoD(f):
lines = open(f, "r+").read().splitlines()
with open("NoD.txt", "w") as NoD:
with open("withD.txt", "w") as withD:
for i, line in enumerate(lines):
if ">No D" in line:
NoD.write(lines[i-2]+"\n"+lines[i-1]+"\n"+lines[i])
else:
withD.write(line+"\n")
如果您这样做,那么当您退出该功能时,文件将自动关闭。