Sorry if this question overlaps the others. I have been searching this title for quite a while now, and still didn't find the answer that can help me. Probably the key words I used are wrong. But here I am.
I had written myself a python script to do some jobs, and the simplified version of my script is as followed:
file = "sample_file.txt"
with open(file, 'r') as f, open("result_file.txt") as w:
for line in f:
new_line = line.split(",")[0]
w.write(new_line + "\n")
But now I would like to re-use this script for new files. So I would like to change my script into a script that does not set the input file name and can take my input file name from the command line. For example:
python_script.py
import fileinput
for line in fileinput.input():
write_out_name = fileinput.filename() + ".txt"
with open(write_out_name, 'w') as w:
new_line = line.split(",")[0]
w.write(new_line)
So I can do in my command line
python3 python_script.py input_file.txt
But apparently my python_script.py does not work, because I got an empty write_out_name.txt. (and I think it's due to the with open
part, as for every line in f
it opens a new file.)
So as a rookie in python scripting, may I ask how to input a user defined file to a python script?
I also tried pandas with df = pd.read_csv(fileinput.input(), sep=' ')
or with fileinput.input() as f: df = pd.read_csv(f, sep=' ')
, and both got complains with errors.
If you think I didn't try enough to search for help and do not like to show me the solution, could you at least point me out some correct key words to search? Thanks!