0

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!

zzz
  • 153
  • 8
  • the issue with your current script is that you are opening and closing a new output file for every line in the input file, which is why your output file is empty. this is code that should work if I understand the problem correctly `input_file = input("Enter input file name: ") output_file = input("Enter output file name: ") with open(output_file, 'w') as w: for line in fileinput.input(input_file): new_line = line.split(",")[0] w.write(new_line + "\n") ` – Seppe Willems Feb 22 '23 at 19:16
  • 1
    I would look into `argparse` for this (see [here](https://docs.python.org/3/library/argparse.html) – Cornelius-Figgle Feb 22 '23 at 19:19
  • 1
    @SeppeWillems please don't put multiline code in comments. If you have an answer to the question, post it as an answer. – MattDMo Feb 22 '23 at 19:30
  • 1
    @SeppeWillems thanks for the quick reply, but I prefer not to have interactively input. I would like to have one liner in the command line, as written above. – zzz Feb 22 '23 at 19:33
  • 1
    Thanks @Cornelius-Figgle! It took me a while to understand how to use `argparse`. Looks very complicated for my level. But after @Pranav Hosangadi point me to a post, then I got the easy way to use it. Thanks to you both! – zzz Feb 23 '23 at 11:39

0 Answers0