【问题标题】:Close fuction dosen´t work when I try with tab or not in Python [closed]当我在 Python 中尝试使用选项卡或不使用选项卡时,关闭功能不起作用[关闭]
【发布时间】:2021-07-24 00:39:48
【问题描述】:

我一直在尝试解决这个简单的问题,但是,我真的不明白为什么会不断发生! 我的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”上,首先我尝试更改制表符位置,但发生同样的错误,然后我使用制表符位置,但同样的情况再次发生。 我真的不明白为什么不起作用。

【问题讨论】:

  • (a, b, c, d, e, f) = line.split("\t") 用字符串覆盖f。使用正确的、说话的名称,不会发生冲突,这样就不会发生。

标签: python fclose


【解决方案1】:

你在这里重新分配f

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

所以在这一点之后f 不是一个文件 - 它是一个字符串。

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

【讨论】:

  • 谢谢,误差很小,实在看不出来。无论如何,再次感谢您!
  • Amit 建议使用 with 是个好主意。
【解决方案2】:

我看到的问题如下:

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

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

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

【讨论】:

    【解决方案3】:

    你正在重新分配给 f 变量

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

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

    你也可以使用 open ,所以你不需要关闭文件

    with open(filename ) as fp:
        #your logic
    

    【讨论】:

    • 使用 with 是个好主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多