@dschika, there are two types of files in this folder, '.raw.fasta' and '.clean.fasta', I need to change the names of .clean.fasta files.
I would have a folder of 8000 files with names
Phy000CVIC_YEAST.raw.fasta
Phy000CVID_YEAST.raw.fasta
Another file (ID.txt) contains ids as
Phy000CVKM YAL001C
Phy000CVKL YAL002W
And I am trying to change files names with IDs in file(ID.txt) with python, what I am doing so far
f = os.listdir('/Users/admin/Desktop/folder')
for f in f:
if f.endswith('.clean.fasta'):
ef=f.split('_')
with open('ID.txt') as id:
for i in id:
i=i.split()
if ef[0]==i[0]:
print(os.rename(f, i[1]))
I am getting the following error
None
None
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
OSError: [Errno 2] No such file or directory
Please guide, where and what is wrong ?
(PS: only two files get renamed out of 8000plus)
2 answers
Look at the error message: "OSError: [Errno 2] No such file or directory"
As you do not provide the whole code I assume the problem is that in your example the file names ended with 'raw.fasta', but in your python script you want to open '.clean.fasta'.
Furthermore, I would recommend you open ID.txt only once and save it into a dictionary. In your code you will open and parse ID.txt 8000 times.
Your code can be better in many ways. As dschika said, you should read you ids file first and rename your files after that. Here is a code I didn't test but may help you.
import glob
import os
dic_ids = {}
with open("ID.txt") as f :
for line in f :
line = line.strip().split()
dic_ids[line[0]] = line[1]
directory = "Users/admin/Desktop/folder/"
fnames = glob.glob(os.path.join(directory, "*.clean.fasta"))
for fname in fnames :
bname = os.path.basename(fname)[:-12]
id = dic_ids.get(bname, None)
if not id :
print("whatever")
else :
newname = os.path.join(directory, id + ".clean.fasta")
os.rename(fname, newname)
Log in to answer this question.
Hello ahmedakhokhar!
We believe that this post does not fit the main topic of this site.
This is not a bioinformatics question. This is a Python question that involves renaming files.
For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.
If you disagree please tell us why in a reply below, we'll be happy to talk about it.
Cheers!