How to write into a file from command line using Python?



In order to write to a file from command line using Python, the script you want to use for it needs to accept a CLI argument.

Example

For example, you want to write a program that appends "Hello" to any file it opens:

import sys
with open(sys.argv[1], 'a') as f:
    f.write("Hello")

Output

If you save this file as cat.py and run it using:

$ python cat.py my_file.txt

Then open my_file.txt, you'll see at the end, Hello is written. The above command will take the my_file.txt and pass it to cat.py as a CLI argument in variable argv[1](second command line argument) which we can use to get the file and read/write to it.


Advertisements