关闭功能剂量当我尝试使用 tab 或不在 Python 中使用选项卡时不起作用



我一直在努力解决这个简单的问题,但我真的不明白为什么会一直发生!我的python脚本:

import re
#### PART 1
#### FIRST: we create a dictionary (an analog of a perl hash)
#### using the file containing two columns= IDS and labels
fileSet = {} ## empty dictionary
fb = open('NT_ID_S.csv', 'r')
for line2 in fb:
if not line2: break
line2 = line2.rstrip("n")
(ax, bx) = line2.split(";")
fileSet[ax] = bx
fb.close()
#### PART 2
#### NOW, we will open our main file and apply while loops to
#### search in parts of every line (nested loops)
f = open('S_dN_dS_Tajima.tsv', 'r')
for line in f: # For main file (with 6 columns)
if not line: break
line = line.rstrip("n")
(a, b, c, d, e, f) = line.split("t")
if (a == "ID1"): continue  ### continue is like "next" in perl; it omits the first line (column names)
if (a == b): continue  ### continue is like "next" in perl; it omits lines where the two IDs are the same
#### Defining empty variables for the future new labels
a3 = None
b3 = None
#### now, we will use the same FOR loop to obtain the value
#### for the labels for the first and second IDs
for key, value in fileSet.items():
if (a == key):
a3 = value
elif (b == key):
b3 = value
#### Printing the final line with the new labels
print (a, "t", b, "t", c, "t", d,"t", e, "t", f, "t", a3 , "t", b3, "t", end="n")
f.close()

错误(在脚本的第二部分(:

File "merge_two_files_JP_v2.py", line 41, in <module>
f.close()
AttributeError: 'str' object has no attribute 'close'

我知道问题出在";f.close";,首先我试图更改选项卡位置,但同样的错误发生了,然后我使用选项卡位置,但是同样的错误再次发生。我真的不明白为什么不起作用。

您在此处重新分配f

(a, b, c, d, e, f) = line.split("t")

因此,在这一点之后,f不是一个文件,而是一个字符串。

这是学习有意义的变量命名的好时机。

我看到的问题如下:

(a, b, c, d, e, f) = line.split("t")

将f的值更改为字符串值。

如果要更改该行中变量f的名称并将f用于文件,则为解决方案。

您正在中重新分配给f变量

(a, b, c, d, e, f) = line.split("t")

您需要更改f以外的变量名。

AL所以你可以使用open,这样你就不需要关闭文件

with open(filename ) as fp:
#your logic

最新更新