File Handling in Python
File Handling in Python
PYTHON
What is File?
A file is the collection of
A file is a location on disk that stores related information and has a name.
Types of Data File
1. Text File:- Text file contains textual information in the form of alphabets,
digits, special characters and symbols as a text document or plain text
document. Text file store data in sequential bytes but bits in text file
represent characters.
Text files are of two types
a) Plain text files: - These files store End of Line (EOL) marker at the end
of each line to represent line break and an End of File (EOF) at the end of
the file to represent end of file.
2. Binary files: - Binary file are those typical file that store data in the form
of sequence of bytes (compiled version of text file) grouped into 8 bit or
sometimes 16 bit. This bit represents custom data and such files can store
multiple types of data (images, audio, text etc.) under a single file.
Opening File
To deal Python file I/O, we have a built-in function open () with a File Object
(should be a valid identifier) in the following mode.
Syntax:-File_Object=open(“FileName”, “Opening_Mode”)
Opening Modes
While opening Python file, we can declare our intentions by choosing a mode. We
have the following modes:
Mode Description
r To read a file (default)
w To write a file; Creates a new file if it doesn’t exist, truncates if it does
x Exclusive creation; fails if a file already exists
a To append at the end of the file; create if doesn’t exist
t Text mode (default)
b Binary mode
+ To open a file for updating (reading or writing)
Examples
#To read and write in binary mode
>>> Myfile=open(“Example.txt”,'r+b')
>>> Myfile=open(“Example.txt”,'a')
Note:-Myfile is the file object, also called File Handle Example.txt is the name
of file and “r+b” is the Opening Mode.
When Python File Doesn’t Exist
Finally, if you try opening Python file that doesn’t exist, the interpreter will throw
a FileNotFoundError.
Now when we call read() without any arguments, it reads the rest of the Python
file.
Notice that it prints a ‘\n’ for a newline. And when we yet read it, it prints an
empty string, because the cursor has reached the end of the Python file.
1. >>> Myfile.read()
2. ''
3. >>> Myfile.close()
We used the ‘end’ parameter to prevent the interpreter from adding extra
newlines to each output. Otherwise, the output would have looked like this:
>>> for line in open(“Example.txt”):
>>>print(line)
d. Readline()
Alternatively, the method readline() lets us read one line at a time. Simply put, the
interpreter stops after every ‘\n’.
Writing to File
To write a Python file, we use the write() method.
1. >>> Myfile =open(“Example.txt”,'a')
2. >>> Myfile.write('\nLearn to cook')
Output: - 14
1. >>> Myfile.close()
When we checked in the file (refreshed it), we found:
Get groceries
Organize room
Print labels
Write article
Study for exam
Concluding, you can use ‘w’, ‘a’, or ‘x’. The ‘w’ erases the content and writes over it.
So, be careful with it. Also, write() returned 14 here because it appended 14
characters to Python file.
But you can’t read a Python file if you open it in ‘a’ mode.
1. >>> Myfile =open(“Example.txt”,'a')
2. >>> Myfile.read()
Error: - Myfile.read()
io.UnsupportedOperation: not readable
To get around this, you’d have to use ‘a+r’.
Output: -
Get groceries
Organize room
Print labels
Write article
Study for exam
Learn to cookWrite to the
Write assignment
One
Two
Three
i. popen()
The popen() method returns a file object that connects to a pipe. In mode ‘w’, we
can write to it, and in mode ‘r’, we can read from it (‘r’ is the default).
Syntax:-
os.popen(command[, mode[, bufsize]])
Here, command is the command we use, and mode is ‘r’ or ‘w’, as discussed
previously. When bufsize is 0, there is no buffering. When it is 1, there is line
buffering when accessing a file. When it is an integer greater than 1, there is
os.rename()
Compiled By: Riteash Kumar Tiwari (VBPSC, Prayagraj)Page 10
OS.rename() is used to python rename file. Like the name suggests, it lets us
rename files and directories.
Syntax of os.rename()
os.rename(src, dst)
Here, src is the source file or directory. dst is the destination file or directory. It
doesn’t return any value.
os.rename() Example
In the following example, we rename the folder ‘NewFolder’ to ‘Photos’.
1. >>> import os,sys
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
3. >>> print(f"We have: {os.listdir()}")
We have: [‘0.jpg’, ‘1.txt’, ‘Documents’, ‘NewFolder’, ‘Today.txt’]
1. >>> os.rename('NewFolder',’Photos’) #This does the renaming
2. >>> os.listdir()
[‘0.jpg’, ‘1.txt’, ‘Documents’, ‘Photos’, ‘Today.txt’]
As you can see, this has renamed the directory ‘NewFolder’ to ‘Photos’. At the time
of writing this article, we tried to rename the directory to the name ‘Documents’.
This raised the following error:
1. >>> os.rename('NewFolder','Documents')
FileExistsError: [WinError 183] Cannot create a file when that file already
exists: ‘NewFolder’ -> ‘Documents’