Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 532397
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:24:01+00:00 2026-05-13T09:24:01+00:00

I’m writing a python script to replace strings from a each text file in

  • 0

I’m writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The output file contains exactly the same text as the original, but with the strings replaced. I need to replace all these strings: ‘K’,’Y’,’W’,’M’,’R’,’S’ with ‘N’.

This is what I’ve come up with after googling. It’s very messy (2nd week of programming), and it stops at copying the files into the clean directory without replacing anything. I’d really appreciate any help.

Thanks before!

import os, shutil

os.mkdir('clean')

for file in os.listdir(os.getcwd()):
    if file.find('.seq') != -1:
        shutil.copy(file, 'clean')

os.chdir('clean')

for subdir, dirs, files in os.walk(os.getcwd()):
    for file in files:
        f = open(file, 'r')
        for line in f.read():
            if line.__contains__('>'): #indicator for the first line. the first line always starts with '>'. It's a FASTA file, if you've worked with dna/protein before.
                pass
            else:
                line.replace('M', 'N')
                line.replace('K', 'N')
                line.replace('Y', 'N')
                line.replace('W', 'N')
                line.replace('R', 'N')
                line.replace('S', 'N')
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T09:24:01+00:00Added an answer on May 13, 2026 at 9:24 am

    some notes:

    1. string.replace and re.sub are not in-place so you should be assigning the return value back to your variable.
    2. glob.glob is better for finding files in a directory matching a defined pattern…
    3. maybe you should be checking if the directory already exists before creating it (I just assumed this, this could not be your desired behavior)
    4. the with statement takes care of closing the file in a safe way. if you don’t want to use it you have to use try finally.
    5. in your example you where forgetting to put the sufix *.clean 😉
    6. you where not actually writing the files, you could do it like i did in my example or use fileinput module (which until today i did not know)

    here’s my example:

    import re
    import os
    import glob
    
    source_dir=os.getcwd()
    target_dir="clean"
    source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]
    
    # check if target directory exists... if not, create it.
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    
    for source_file in source_files:
       target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")
       with open(source_file,'r') as sfile:
          with open(target_file,'w') as tfile:
             lines = sfile.readlines()
             # do the replacement in the second line.
             # (remember that arrays are zero indexed)
             lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])
             tfile.writelines(lines)
    
    print "DONE"
    

    hope it helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 484k
  • Answers 484k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The amount of data transferred (or not) with RIA services… May 16, 2026 at 7:25 am
  • Editorial Team
    Editorial Team added an answer Your logger should probably be static, and you can take… May 16, 2026 at 7:25 am
  • Editorial Team
    Editorial Team added an answer boolean hasRows = false; while(rs.next()){ hasRows = true; // do… May 16, 2026 at 7:24 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.