How to extract part of a filename used in a python script as an argument?

Viewed 995

I know, the title sounds a bit confusing, and as a newbie in Python I didn't know how to put it a better way.

Here's what I want to do:

My script will read csv files (spreadsheets) and create new spreadsheets from them that won't contain anything else but numbers. Basically, this script gets rid of unwanted character strings by deleting the rows and columns that contain them. I managed to create a functioning script, although it can only be applied to a single file. Put it another way, I would need to change the input file name inside the script each time I want to run it on another csv file.

My files have names of this type: "MODELXXXXXXXXX__NAMEY_alfaZ.csv" where X, Y and Z are numbers. I want to pass these files' name as an input to my Python script, so I've used the sys.argv[1] syntax in order to achieve that. Here is an example of what my code looks like:

import csv
import sys

strings_to_remove = ['string1','string2']

with open(sys.argv[1],'rb') as oldfile, open('NAMEY_alfaZ_test1.csv','w+b') as newfile:
    for line in oldfile:
        if not in any(strings_to_remove in line for strings_to_remove in strings_to_remove):
            newfile.write(line)

I run my script like this:

python script.py MODELXXXXXXXXX_NAMEY_alfaZ.csv

Now what I'd like to do is automate my script, that is to get rid of the "MODELXXXXXXXXX" part and not having to write "NAMEY_alfaZ" for the output file each time I want to apply my script to another file.

Is there any way to do that?

Thanks

3 Answers
Related