Hello, in this tutorial we will learn how to Read, Write, Report, Search, Check Status, Move, Copy and Delete a Python file, with some practical examples to make it easier to understand, but first of all we will see Python file operating modes.
Python file operating modes.
In Python, there are file operating modes available for file processing, which are:
w → write mode (if the file does not exist, create it and open it in write mode)
r → read
mode a → mode attach (if the file does not exist, create it and open it in attach mode)
w + → create a file - if it does not exist and open it in write mode
r + → open an existing file in read mode + write
a + → create a file - if it doesn't exist and open it in attach mode
Read file in python
Reading a file in python is very simple, use the open function to open it and then use the read function to read the file , see the example below.
f = open("example.txt", "r") #opening the file in read mode
c = f.read() #reading the file
print(c)
f.close() #Closing the file
The open function takes two arguments, the first one that is before the comma, there we will pass the file we want to open, and the second argument that is after the comma here we will pass the mode we want to open the file, in this example we use themode r which is open for reading (default), this mode if the file does not exist will return an error.
In the example below we open the file in w+ mode which is create a file - if it doesn't exist and open it in write mode.
#create a file - if it doesn't exist and open it in write mode.
f = open("example.txt", "w+")
c = f.read() #reading from file
print(c)
f.close() #Closing file
Write to a file in Python
The simplest way to write to a Python file is using the write function, see example below:
f = open("example.txt", "w")
f.write("using Python") #writing to file
f. close()
Closing a file in Python
It is necessary to always close the file after any operation, otherwise it can cause memory leaks. Sometimes read or write operations can throw an exception. In this scenario, the file will not close correctly. This can lead to unexpected program behavior and can lead to a resource leak.
To ensure that the file is closed every time it is opened, we must follow one of the approaches below.
To ensure that the file is closed every time it is opened, we must follow one of the approaches below.
Method 1
try:
f = open("example.txt", "w+")
f.write("Using Python")
except Exception as e:
print(e)
finally:
f.close()
Method 2
#Read a file
with open("example.txt", "r") as f:
c = f.read()
print(c)
#Write to a file
with open("example.txt", "w") as f:
f.write ("hello")
So when we open a file using with, we don't have to worry about closing the file. All cleaning is done automatically by Python.
Python Files - Methods for Reading and Writing to a File
First, we'll look at three methods we can use to read files, and they are:
Read ( read )method:
The read() method reads the entire contents of the file at once. This method also accepts one parameter, size. This is the number of characters or bytes to be read.
with open("example.txt", "r") as f:
print(f.read())
Read method ( readline ) :
The readline() method reads only one line at a time. This method also accepts one parameter, size. This is the number of characters or bytes to be read.
To get all the lines, use a loop until we get non-empty lines.
Let's see an example of reading a file one line at a time.
with open("example.txt", "r") as f:
line = f.readline()
while line != "":
print(line)
line = f.readline()
Read method ( readlines ):
The readlines method () also fetches the entire contents of the file at once. The return type of this method is a list of lines.
with open("example.txt", "r") as f:
print(f.readlines())
This method also takes one parameter, hint. the readlines method stops reading lines as the number of characters exceeds more than the hint.
For example, look at the code below will read two lines, because after reading two lines, the number of characters will exceed the hint, 18.
with open("example.txt", "r") as f:
print(f. readlines(18))
The readlines method is memory efficient as it reads one line at a time.
Now we will see 2 methods we can use to write to files, and they are:
method ( Writewrite ):
Write the contents to the file, see the example below:
with open("example.txt", "w") as f:
f .write("I also like to use Python")
method ( Writewritelines ):
Write the list of lines / text in the file.
pais = [] #empty list
pais.append("Angola") #added values to the list
pais.append("Brazil") #added values to the list
pais.append("Portugal") #add values to the list pais
with open("example.txt", "w") as f:
f.writelines(parents)
Working with files in Python
Here we are going to delve into how to work with files in Python, performing various operations and using different methods that exist in Python.
Moving the cursor inside the file
The method tell() is used to find the current cursor location within the file.
The seek(offset, where) method is used to move the pointer with the given offset, corresponding to where. Hence you can have one of the values below.
0 → from the beginning of the file.
1 → current cursor location.
2 → from the end of the file. This value can only be used in binary mode.
with open("example.txt", "r") as f:
print(f.tell())
print(f.seek(1))
print(f.tell())
print(f.read())
Output:
0
1
1
ngola Brazil Portugal
Using Python and like
Using Python again
we are using Python
and you are using Python
[Finished in 0.4s]
0 is the location current cursor.
1 is the cursor location after the seek operation.
1 is the current cursor location as reported by the tell operation.
The next three lines are the contents of the file returned by the read() method. Note the missing 2 characters that were skipped due to the seek() operation.
If you are skipping characters from the end of the file
with open("example.txt", "rb") as f:
print(f.tell())
print(f.seek(-10, 2))
print(f.tell ())
print(f.read())
Also note that the file mode must be binary, 'rb' in the example above. If you try to use the seek operation on a file opened in text mode, that is, in 'r' mode, you will get the error.
with open("example.txt", "r") as f:
print(f.tell())
print(f.seek(-10, 2))
print(f.tell())
print(f.read( ))
Checking the status of a file
You can use thefunction stats module's os to check the statistics of a file.
import os
print(os.stat("main.py"))
Output
os.stat_result (st_mode=33206, st_ino=1125899907082210, st_dev=3193403517, st_nlink=1, st_uid=0, st_gid=0, st_size=38, st_atime=1624244145, st_mtime=1624244142, st_ctime=1622476866)
[Finished]
object in 1.9 contains mode, inode number, number of links, user id, group id, size in bytes, access time, modification time and creation time.
Copying a file
To copy a file, we can use thefunction system() from themodule os or thefunction copy from themodule shutil.
The copy function will not copy file metadata such as access time and modification time.
import
os.system("copy main.py file_copy")
import shutil
shutil.copy("main.py", "file_copy.py")
The copy2 function will copy the metadata like access time or file modification time together with the file. This can be verified using the os.stats("file") function call.
import shutil
shutil.copy2("main.py", "file_copy.py")
The copyfile function will not copy file permissions. The newly copied file will have default system permissions.
import shutil
shutil.copyfile("example.txt", "Copy_file")
Moving a file
There are three ways to move a file, and let's see them
Using themethod system of themodule os.
os.system("mv location where the file is located")
Using themethod rename of themodule os.
os.rename("source path", "destination path")
using the move method of themethod shutil.
shutil.move("source path", "destination path")
Deleting a file
There are two ways to delete a file.
Using themethod remove from themodule OS.
os.remove("where the file is located")
using themethod system of themodule os.
os.system("rm is where the file is located")
Post a Comment
0Comments