Files - Introduction
The open() function helps us to read from or write to a file.
The syntax for the open function is as below.
FILEHANDLE = open(FILEPATH, ACCESSMODE, BUFFERINGOPTIONS)
The access modes are read, write, append (add to existing file data). This is an optional parameter as the default open mode is read.
r indicates read
w indicates write
a indicates append
a+ indicates both read and append
The below program opens a file called input.txt and prints the content in it.
fh = open("input.txt","r")
print (fh.read())
fh.close()
The method read() reads the entire content in the file.
The method close() releases the filehandle.
Files - Writing to a file
The write() function helps us to write to a file.
The below program opens a file called output.txt and writes a single like "This is the first line" to the file.
f = open("output.txt","w")
f.write("This is first line")
f.close()
The method close() flushes the buffer to the file and releases the filehandle.
Files - Appending content to a file
A file can be opened in append mode and the write() function can be used to append content to the file.
The below program opens a file called output.txt and appends the string "Rocks Stones".
f = open("output.txt","a")
f.write("Rocks Stones")
f.close()
If the file content initially was
First Line
Second Line
then the revised content will be
First Line
Second LineRocks Stones
To append the content in a new line (next line), the following code can be used with a \n
f = open("output.txt","a")
f.write("\nRocks Stones")
f.close()
Another example program:
The content of output.txt is as below
Actor1 - ABCD
Actor2 - EFGH
f = open("output.txt","a")
f.write("\nActor3 - IJKL")
f.close()
#Print the file content as output
f = open("output.txt","r")
print (f.read())
f.close()
Now output.txt contains
Actor1 - ABCD
Actor2 - EFGH
Actor3 - IJKL
Files - with open
A better way to open files is to use with open.
The below program shows how to open a file using open and print the content in it.
with open("output.txt","r") as f:
line in f:
print (line, end="")
The content of data.txt is as below
FirstLine
SecondLine
ThirdLine
FourthLine
FifthLine
SixthLine
with open("data.txt","r") as f:
for count,line in enumerate(f, start=1):
if count % 2 == 1:
print (line, end="")
That is the output of the program is as below.
FirstLine
ThirdLine
FifthLine
File I/O - readline()
The readline() method can be used to read a single line from a file from the current position. The below program prints the first four lines present in the file data.txt
with open("data.txt","r") as f:
for line in range(1,5):
print (f.readline(), end="")
File I/O - random line access
The linecache module can be used to randomly access a line in a file.
The below program prints the 11th line in the file data.txt
import linecache
print (linecache.getline("data.txt",11), end="")
the below program prints the Nth line in the file data.txt
n = int(input())
import linecache
print (linecache.getline("data.txt",n))
File I/O - seek method
The syntax of seek method is
f.seek(offset, from_what)
offset refers to the byte count from the position mentioned by from_what.
- If from_what is 0, then it means from the beginning of the file. This is the default value.
- If from_what is 1, then it means from the current position of cursor.
- If from_what is 2, then it means from the end of the file.
The below program prints the content in the file data.txt from the 6th byte (character). (As the index starts from zero, 5 denotes 6th byte)
with open("data.txt","r") as f:
f.seek(5)
print (f.read())
If the content of the file is abcdefghijklmnop, then the output of the program is fghijklmnop
Renaming a file
The os module helps in renaming a file.
The below program renames data.txt to data1.txt
import os
os.rename("data.txt","data1.txt")
fileinput module helps to perform inplace edit on files.
Let us consider the file data.txt which contains the following content.
banana
apple
berry
melon
Files - Inplace edit
We wish to append an asterisk in the end , if the line starts with the letter b. The below program produces the desired output given below which is now the content of data.txt
apple
banana*
melon
berry*
import fileinput
for line in fileinput.input('data.txt', inplace=1):
if line.startswith('b'):
print (line.rstrip()+"*")
else:
print (line, end="")
The print will redirect the content to the file being edited inplace rather than the standard output.
We do the rstrip() to remove the new line character in the end so that we can append the asterisk in the end. The new line is automatically added by the print statement as we have not overridden the default behaviour using the end parameter.
Comments
Post a Comment