I have been trying to solve this easy problem, however, I really don't understand why keeps happening! My python script:
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()
The error (in the second part of the script):
File "merge_two_files_JP_v2.py", line 41, in <module>
f.close()
AttributeError: 'str' object has no attribute 'close'
I know that the problem is with "f.close", first I tried to change the tab position but the same error happens, then I use the tab position, however the same happens again. I really don´t understand why doesn't work.
You reassign f
here :
(a, b, c, d, e, f) = line.split("\t")
So after this point f
isn't a file - it is a string.
This is a good time to learn meaningful variable naming.