Earlier you have learned about how to get input from the user using input and argv method. In this article, you will learn about how to read from a file and various functions that are important for file handing using Python 3.
List of functions you will study in this post regarding File Handling.
| Name of the Function | Role of Function |
|---|---|
| open | It is use to open the given file. |
| close | Closes the file. |
| read | Reads the contents of the file. You can assign the result to a variable. |
| readline | Reads just one line of a text file. |
| truncate | Empties the file. |
| write('stuff') | Writes “stuff” to the file. |
| seek(0) | Moves the read/write location to the beginning of the file. |
Program Implemetation: Open | Truncate | Write | Close
Code:
from sys import argv
program_name, filename = argv
print("We are going to erase the content of the given file first, if the file exists")
print("Opening the File....")
destination = open(filename, 'w')
print("Erasing the content of the file....")
destination.truncate()
print("Now Enter the data you want: In three lines")
Line1 = input("Line 1: ")
Line2 = input("Line 2: ")
Line3 = input("Line 3: ")
print("These three lines will be written")
destination.write(Line1)
destination.write("\n")
destination.write(Line2)
destination.write("\n")
destination.write(Line3)
destination.write("\n")
print("Now the file is set to close")
destination.close()
Output:
We are going to erase the content of the given file first, if the file exists Opening the File.... Erasing the content of the file.... Now Enter the data you want: In three lines Line 1: I love Python Programming Line 2: I love to code using Python Line 3: I am good at Python Programming These three lines will be written Now the file is set to close
Program Implementation: Copy data of One File to Another
Code:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# we could do these two on one line, how?
input_file = open(from_file)
input_data = input_file.read()
print(f"The input file is {len(input_data)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
output_file = open(to_file, 'w')
output_file.write(input_data)
print("File is Copied Successfully")
Output:
Copying from sample.txt to sample_copy.txt The input file is 86 bytes long Does the output file exist? False Ready, hit RETURN to continue, CTRL-C to abort. File is Copied Successfully