问题
I am trying to read in some data, process the data, and write the results to a CSV saved with original file name + the word "folded". I'm using sys.argv
to pass the input filename, and thought that I could just create a new variable such as filename = sys.argv[1]+'_folded.csv
but I ended up with file.csv_folded.csv
.
How can I do this so my output file is saved as file_folded.csv?
Simplified code example:
import sys
import networkx as nx
G = nx.read_edgelist(sys.argv[1], delimitier=',')
fileout = sys.argv[1]+'_folded.csv'
nx.write_edgelist(G, fileout, delimiter=',')
回答1:
It looks like you are already specifying filename.csv
in your command line argument so you want to replace that with your special extension to do that you could:
file_name = sys.argv[1].replace('.csv', '_folded.csv')
回答2:
Split the file extension and only use the prefix:
orginal_name = sys.argv[1]
prefix = orginal_name.rsplit('.')[0]
fileout = prefix + '_folded.csv'
or just pass the out
file name from terminal (which I prefer), for example:
python program.py file.csv file_folded.csv
Then in code just use sys.argv[2]
for out
file name.
回答3:
You could slice
the .csv off of sys.argv[1]:
fileout = sys.argv[1][:-3] +'_folded.csv'
来源:https://stackoverflow.com/questions/24409984/append-word-to-input-file-name-for-output-file-name