2

I need to rename many files with the following format:

509938_OPS001_ACTCGCTA-TCGACTAG_L001_R1_001.fastq.gz

I've tested my regex:

\d+\w([OPS]+\d+)[_]\w+-\w+[_](\d+)(\.fastq\.gz)

I've tried many versions of the following script, but each throws a syntax error following re.sub.

import glob, re, os

for filename in glob.glob('some/dir/*.fastq.gz'):
    new_name = re.sub(\d+\w([OPS]+\d+)[_]\w+-\w+[_](\d+)(\.fastq\.gz), r'\1_\2\3', filename)
    os.rename(filename, new_name)

$python fastq_rename.py
  File "fastq_rename.py", line 6
    new_name = re.sub(\d+\w([OPS]+\d+)[_]\w+-\w+[_](\d+)(\.fastq\.gz)), r'\1_\2\3', filename)
                                                                                            ^
SyntaxError: unexpected character after line continuation character

Presuming this has to do with an unescaped backslash, I've enclosed the regex with r' ', and this avoids the error, but does not change filenames.

1 Answer 1

1
new_name = re.sub(r'\d+\w([OPS]+\d+)[_]\w+-\w+[_](\d+)(\.fastq\.gz)', r'\1_\2\3', filename)
new_name="some/dir/"+newname

Enclose regex in r.Also the newname parameter to os.rename should include filepath or else it will rename file to the directory from where script if being called.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, the filepath was key!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.