Files
Files
So far, we've taken input from the console, written it back to the console,
and interacted with the user.
Displaying data in the console may not be enough. Since memory is volatile
and it is impossible to recover the data generated by the program many
times, the displayed data can be very large and only a limited amount of
data can be displayed on the console. Can not be displayed.
Each line of a file is terminated with a special character, called the EOL or
End of Line characters like comma {,} or newline character. It ends the
current line and tells the interpreter a new one has begun.
They are:
Binary file
Text file
In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
Example:
1. Document files: .pdf, .doc, .xls etc.
2. Image files: .png, .jpg, .gif, .bmp etc.
3. Video files: .mp4, .3gp, .mkv, .avi etc.
4. Audio files: .mp3, .wav, .mka, .aac etc.
5. Database files: .mdb, .accde, .frm, .sqlite etc.
6. Archive files: .zip, .rar, .iso, .7z etc.
7. Executable files: .exe, .dll, .class etc.
8. All binary files follow a specific format. We can open some binary files
in the normal text editor but we can’t read the content present inside
the file. That’s because all the binary files will be encoded in the binary
format, which can be understood only by a computer or machine.
9. For handling such binary files we need a specific type of software to
open it.
10. For Example, You need Microsoft word software to open .doc
binary files. Likewise, you need a pdf reader software to open .pdf
binary files and you need a photo editor software to read the image
files and so on.
In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by
default.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
In Python, files are treated in two modes as text or binary. The file may be in
the text or binary format, and each line of a file is ended with the special
character.
o Open a file
o Read or write - Performing operation
o Close the file
Python provides an open() function that 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:
The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.
S Access Description
N mode
1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access
mode is passed.
3 r+ It opens the file to read and write both. The file pointer exists at
the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at
the end of the previously written file if exists any. It creates a
new file if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains
at the end of the file if a file exists. It creates a new file if no file
exists with the same name.
12 ab+ It opens a file to append and read both in binary format. The
file pointer remains at the end of the file.
In addition you can specify if the file should be handled as binary or text
mode
Creating a file
Example 1:
# By using “x”mode
f=open("newdata.txt","x")
Output:
Note: newdata.txt will be an empty file
Example 2:
#by using “w” mode
f=open("latestdata.txt","w")
text="this file is created using 'w' mode"
f.write(text)
Output:
There is more than one way to read a file in Python. If you need to extract a
string that contains all characters in the file then we can use file.read().
Example 1:
# To create a file and read it’s contents
Create:myfile.py
f=open(“data.txt”,”r”)
print(f.read())
Output:
Example 2:
f=open("data.txt","r")
print(f.read(10))
Example 3:
data.txt:
myfile.py
f=open("data.txt","r")
print(f.readline())
print(f.readline())
print(f.readline())
Output:
This is a text file
1. This is line 1
2. This is line 2
1. opening a file in ”a” mode (Append - will append to the end of the file)
2. opening the file in “w” mode (Write - will overwrite any existing
content)
Note:
In the case of append mode, the contents written will be appended/added
at the end of file while in the case of write mode the previous contents will
be overwritten.
Example:
# using append mode
f=open("data.txt","a")
f.write("\n")
text='''Now some data will be added
6. This is line 6
7.This is line 7
8. This is line 8'''
f.write(text)
Output:
Example:
# using write mode
f=open("data.txt","w")
f.write("\n")
text='''Now some data will be added
6. This is line 6
7.This is line 7
8. This is line 8'''
f.write(text)
Output:
Closing a File
It is a good practice to always close the file when you are done with it. The
close() command terminates all the resources in use and frees the system
of this particular program.
Example 1:
f=open("data.txt","r")
print(f.read())
f.close()
Example 2:
f=open("data.txt","r")
print(f.read())
f.close()
print(f.read())
Output:
Deleting a File
Example:
# To delete latestdata.txt
import os
os.remove("latestdata.txt")
Check if File exist
There may be a situation where you want to check whether a file exists or
not before any kind of further processing. For this we can use following code.
Example:
import os
if os.path.exists("latestdata.txt"):
else:
Output:
Delete Folder
Example:
import os
os.rmdir("myfolder")
The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used in the scenario where a
pair of statements is to be executed with a block of code in between. The
advantage of using with statement is that it provides the guarantee
to close the file regardless of how the nested block exits.
Syntax:
Example:
with open("file.txt",'r') as f:
content = f.read();
print(content)
A file pointer denotes the position from which the file contents will
be read or written. File handle is also called as file pointer or cursor.
The seek() function sets the position of a file pointer. Python provides us the
seek() method which enables us to modify the file pointer position externally.
Syntax:
<file-ptr>.seek(offset, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be
moved.
The allowed values for the from argument are: –
In short, The seek() function sets the position of a file pointer and
the tell() function returns the current position of a file pointer.
Example:
fileptr = open("data.py", "r")
Output:
Python OS module
The mkdir() method is used to create the directories in the current working
directory. The syntax to create the new directory is given below.
Syntax:
mkdir(directory name)
Example:
import os
#creating a new directory with the name new
import os
os.mkdir("New Folder")
Output:
Note: Here, a new folder is created with the name “New Folder”
Renaming a directory
Syntax:
rename(current-name, new-name)
The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two
arguments.
Example:
import os
os.rename("New Folder","Latest Folder")
Output:
Syntax:
os.getcwd()
Example:
import os
print(os.getcwd())
Output:
C:\Users\Administrator\PycharmProjects\pythonProject
Syntax:
chdir("new-directory")
Example:
import os
print(os.getcwd())
os.chdir("C:\\Users\\IINTM\\Documents")
#It will display the current working directory
print(os.getcwd())
Output:
C:\Users\Administrator\PycharmProjects\pythonProject
C:\Users\IINTM\Documents
The file object provides the following methods to manipulate the files on
various operating systems.
SN Method Description