Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing i with increasing numbers

I’m brand new to python so I apologize in advance. I need help renaming hundreds of files.

Currently my files look like this:
SRR3521304001.fastq
SRR3521305001.fastq
SRR3521306001.fastq

I would like my files to be renamed into the following format:
SRR3521304_S(i)_L001_R1.fastq
SRR3521305_S(i)_L001_R1.fastq
SRR3521306_S(i)_L001_R1.fastq

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need i to be a number that starts at 1 and increases.

This is what I have tried so far:

import os

files = os.listdir('joined_reads')
i = 1

for file in files:
    name = file.replace('001.fastq','S{i}_L100_R1_001.fastq')
    os.system('cp,   joined_reads/' + file + ' new/' + name)
    i+=1

This gives me files that look like SRR3521304_S(i)_L001_R1.fastq. Can someone help me change the i to an increasing number?

>Solution :

To use {i} you need to use f before your string to format it accordingly. Also you could use enumerate with the start value at 1.

import os

files = os.listdir('joined_reads')

for i, file in enumerate(files, 1):
    name = file.replace('001.fastq',f'S{i}_L100_R1_001.fastq')
    os.system('cp,   joined_reads/' + file + ' new/' + name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading