Python Menu

Files in Python


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.

  • Open a file
  • Read or write (perform operation)
  • Close the file

File Built-in Function [open ()]

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)
Example:
fileptr = open("myfile.txt","r")  
if fileptr:  
    print("file is opened successfully with read mode only") 
Output:
file is opened successfully with read mode only
Example:
fileptr = open("myfile1.txt","x")  
if fileptr:  
    print("new file was created successfully") 
Output:
new file was created successfully

File Built-in Methods

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

  • close()
  • read()
  • readline()
  • write()
  • writelines()
  • tell()
  • seek()

☞ close()

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.

Syntax:
Fileobject.close()

Example:
f = open("myfile.txt", "r")
f.close()

☞ read()

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.

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
# 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();
Output:
file is opened successfully
funct
ion open() to open a file.
method read() to read a file.

☞ readline()

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()

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
fileptr = open("myfile.txt","r")
if fileptr:
	print("file is opened successfully")
	content=fileptr.readline()
	print(content)
	content=fileptr.readline()
	print(content)
fileptr.close();
Output:
file is opened successfully
function open() to open a file.
method read() to read a file.

☞ write()

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)

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
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();
myfile.txt:
Python is the modern day language.

a: It will append the existing file. The file pointer point at the end of the file.

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
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(); 
myfile.txt:
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.

☞ writelines()

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.

Example:
f = open("myfile.txt", "w")
f.writelines(["Python supports Files \n", "python supports Strings."])
f.close()
myfile.txt:
Python supports Files
python supports Strings.

File Positions

Methods that set or modify the current position within the file

☞ tell()

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()

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
f = open("myfile.txt", "r")
print(f.readline())
print(f.tell())
f.close();
Output:
33

In the fist line of file that is "function open() to open a file." with 32 charecters so the output is 33

☞ seek()

The seek() method sets and returns the current file position in a file stream.

Syntax:
Fileobject.seek(offset)

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
Output:
open() to open a file.
method read() to read a file.

First We moved 9bytes with seek function and then started reading

File Built-in Attributes

Python Supports following built-in attributes, those are

  • file.name - returns the name of the file which is already opened.
  • file.mode - returns the access mode of opened file.
  • file.closed - returns true, if the file closed, otherwise false.
Example:
f = open ("myfile.txt", "r")
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
Output:
myfile.txt
r
False
True

Python program to print number of lines, words and characters in given file.

myfile.txt
function open() to open a file.
method read() to read a file.
Python is the modern day language.
Python supports Files 
python supports Strings	
Example:
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")
Output: Case 1
Enter file name: myfile.txt
Lines =  5
Words =  24
Characters =  144
Output: Case 2
Enter file name: gh
Enter valid filename

Next Topic :Command-Line Arguments in Python