- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
For example, you want to write a program that appends "Hello" to any file it opens:
import sys with open(sys.argv, 'a') as f: f.write("Hello")
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(second command line argument) which we can use to get the file and read/write to it.
- Related Articles
- How to read a file from command line using Python?
- How to write a single line in text file using Python?
- How to run Python functions from command line?
- How to call Python module from command line?
- How to read an entire line from a text file using Python?
- How to Pretty print Python dictionary from command line?
- How to send a file as an email attachment using the Linux command line?
- How to write binary data to a file using Python?
- How to read complete text file line by line using Python?
- How to Write a List Content to a File using Python?
- How to Delete Specific Line from a Text File in Python?
- How to run TestNG from command line?
- How to merge multiple files into a new file using Python?
- How to concatenate two files into a new file using Python?
- How to spilt a binary file into multiple files using Python?