Till now, we were taking the input from the console and writing it back to the console to interact with the user. Instead of that we can able use files as input or output.
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
Python has a built-in function open() to open a file. Which accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.
Syntax:Fileobject = open (file-name, access-mode)
file-name: It specifies the name of the file to be opened.
access-mode: There are following access modes for opening a file:
access-mode | Description |
---|---|
"w" |
Write - Opens a file for writing, creates the file if it does not exist. |
"r" |
Read - Default value. Opens a file for reading, error if the file does not exist. |
"a" |
Append - Opens a file for appending, creates the file if it does not exist. |
"x" |
Create - Creates the specified file, returns an error if the file exists. |
"w+" |
Open a file for updating (reading and writing), overwrite if the file exists. |
"r+" |
Open a file for updating (reading and writing), doesn’t overwrite if the file exists. |
In addition you can specify if the file should be handled as binary or text mode
access-mode | Description |
---|---|
"t" |
Text - Default value. Text mode. |
"b" |
- Binary - Binary mode (e.g. images) |
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully with read mode only")
file is opened successfully with read mode only
fileptr = open("myfile1.txt","x")
if fileptr:
print("new file was created successfully")
new file was created successfully
Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. For this, python provides following built–in functions, those are
The close() method used to close the currently opened file, after which no more writing or Reading can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
Fileobject.close()
f = open("myfile.txt", "r")
f.close()
The read () method is used to read the content from file. To read a file in Python, we must open the file in reading mode.
Syntax:Fileobject.read([size])
Where ‘size’ specifies number of bytes to be read.
function open() to open a file.
method read() to read a file.
# Opening a file with read mode
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully")
content = fileptr.read(5) #read 5 characters
print(content)
content = fileptr.read() #read all characters
print(content)
else:
print("file not opened ")
fileptr.close();
file is opened successfully
funct
ion open() to open a file.
method read() to read a file.
Python facilitates us to read the file line by line by using a function readline(). The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.
Syntax:Fileobject.readline()
function open() to open a file.
method read() to read a file.
fileptr = open("myfile.txt","r")
if fileptr:
print("file is opened successfully")
content=fileptr.readline()
print(content)
content=fileptr.readline()
print(content)
fileptr.close();
file is opened successfully
function open() to open a file.
method read() to read a file.
The write () method is used to write the content into file. To write some text to a file, we need to open the file using the open method with one of the following access modes.
w: It will overwrite the file if any file exists. The file pointer point at the beginning of the file in this mode.
Syntax:Fileobject.write(content)
function open() to open a file.
method read() to read a file.
fileptr = open("myfile.txt","w");
#appending the content to the file
fileptr.write("Python is the modern day language.")
#closing the opened file
fileptr.close();
Python is the modern day language.
a: It will append the existing file. The file pointer point at the end of the file.
function open() to open a file.
method read() to read a file.
fileptr = open("myfile.txt","a");
#appending the content to the file
fileptr.write ("Python is the modern day language.")
#closing the opened file
fileptr.close();
function open() to open a file.
method read() to read a file.
Python is the modern day language.
Now, we can see that the content of the file is modified.
The writelines () method is used to write multiple lines of content into file. To write some lines to a file
Syntax:Fileobject.writelines(list)
list − This is the Sequence of the strings.
f = open("myfile.txt", "w")
f.writelines(["Python supports Files \n", "python supports Strings."])
f.close()
Python supports Files
python supports Strings.
Methods that set or modify the current position within the file
The tell() method returns the current file position in a file stream. You can change the current file position with the seek() method.
Syntax:Fileobject.tell()
function open() to open a file.
method read() to read a file.
f = open("myfile.txt", "r")
print(f.readline())
print(f.tell())
f.close();
33
In the fist line of file that is "function open() to open a file." with 32 charecters so the output is 33
The seek() method sets and returns the current file position in a file stream.
Syntax:Fileobject.seek(offset)
function open() to open a file.
method read() to read a file.
f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
open() to open a file.
method read() to read a file.
First We moved 9bytes with seek function and then started reading
Python Supports following built-in attributes, those are
f = open ("myfile.txt", "r")
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
myfile.txt
r
False
True
Python program to print number of lines, words and characters in given file.
function open() to open a file.
method read() to read a file.
Python is the modern day language.
Python supports Files
python supports Strings
fname = input("Enter file name: ")
num_lines = 0
num_words = 0
num_chars = 0
try:
fp=open(fname,"r")
for i in fp:
# i contains each line of the file
words = i.split()
num_lines += 1
num_words += len(words)
num_chars += len(i)
print("Lines = ",num_lines)
print("Words = ",num_words)
print("Characters = ",num_chars)
fp.close()
except Exception:
print("Enter valid filename")
Enter file name: myfile.txt
Lines = 5
Words = 24
Characters = 144
Enter file name: gh
Enter valid filename