Reputation: 822
newbie python programmer here. I have written a script and want to modify the start so that it runs through files in a folder, so I don't have to change input and output file extensions each time.
The folder of input files contains chromosome files such as 'chr1', 'chr2', 'chrx' etc. I want to output to a different folder and pathway and use the input files as the basis for the outputfile, while also adding an extension such as 'windowstatistics'. For example then the input file 'chr1' would be output in a different folder as 'chr1windowstatistics'.
I have been trying to solve this for a couple of days without getting a working solution.
Currently I have:
import os
import glob
path = '/man/genotyping/Conservation/splitbychrom/'
for infile in glob.glob( os.path.join(path, 'Chr*') ):
inputfile = open(infile, 'r')
output = os.rename(inputfile + ".out", 'w')
Does anyone know how to get this working, I don't mind if the way it is done is quite different, I just want to be able to run the script once and it iterates through the files.
Please let me know if I need to reformulate the question for clarity. Thanks in advance for all your help. It is really appreciated.
Upvotes: 0
Views: 2262
Reputation: 471
To rename a file: os.rename(infile, infile + ".out")
os.rename takes two strings: source path, target path. The assignment to "output" is unused.
To copy a file (in *nix): os.system ("cp " + infile + " " + infile" + ".out")
Upvotes: 0
Reputation: 91017
Just write down what you want - which is unclear to me.
Do you want to rename? Then tell os.rename()
what you want to rename and to what. In your case, you want to rename the orognal file to a new name which is certainly not w
. So do os.rename(infile, newfilename)
.
Do you want to process and put the output data somewhere else? Then open the file for writing, and with the correct file name: do output = open(infile + ".out", 'w')
.
Especially don't confuse filenames with file objects and how the functions work in particular.
Upvotes: 1