File operations in python

by Alex
File operations in python

The basic capabilities of the Python programming language allow you not only to manipulate data in text documents, but also to manipulate them. For this purpose there are several special libraries with built-in functions for copying, deleting, renaming, and other kinds of operations with files on your computer.

Checking for the existence of a file

Avoid annoying mistakes when working with a text document, which can be associated with its absence on your hard drive, method exists from module os can help. Calling this method in Python verifies the existence of the file in the path and gets a boolean answer: True or False. To use this method, you first need to include the os library and then call exists on the path class. The following Python example shows how to check if the files test.txt and test10.txt exist in the root directory of hard drive D. The print function shows that only the first document is present on D.

import os
print(os.path.exists("D:\test.txt"))
print(os.path.exists("D:\test10.txt"))

True
False

Sometimes when working with documents, there’s a need to check if some object doesn’t only exist in a specified path. The function isfile from the above mentioned os library allows the programmer to make sure that the object at a certain address on the hard disk is a file and not a folder. This method is also found in the path class. The following example shows how isfile reacts to a test.txt file and a folder in the root of D. As you can see from the results of the print function, the first one shows True and the second one False.

import os
print(os.path.isfile("D:\test.txt"))
print(os.path.isfile("D:\folder"))

True
False

You can also check if the file is present at the specified address using the open function with as clause. This method opens a document so the program can interact with its contents. If the open function was able to execute without errors, it means that there is a file at the path given to it as an argument. If an exception occurs, then the file could not be opened. That does not mean it does not exist. Perhaps, for example, there are not enough permissions to access it. In the example below, the program uses the print method to tell you if the document you are looking for exists. The output shows that the file is open.

try:
    with open("D:\test.txt") as file:
        print("file is open")
except:
    print('no open')

file is open

Copying a file

The shutil library includes some useful functions to create copies of objects on your hard disk. To make a quick copy of a file to its source directory, you can use the copyfile method with the shutil module first. The first argument here is the original document, while the second parameter is the intended new file. Keep in mind that only the content is copied, not the metadata. The following example copies the data from test.txt to test2.txt on drive D. The copyfile function also returns the address of the created document.

import shutil
shutil.copyfile("D:\test.txt", "D:test2.txt")

The built-in copy method of the shutil module allows Python to copy a file to a specified folder while keeping its original name. The following code example shows copying information from test.txt to an object located on the D drive in a directory called folder. As in the previous copyfile function, only the internal data is copied but not the date when the document was created or edited.

import shutil
shutil.copy("D:\test.txt", "D:folder")

To fully copy the information from a text file and all the information about it, you need to use the ready-made copy2 method. The way to use it is the same as with the copy function. In place of the first argument, it takes the address of the original file, while the second argument tells you the location and name of the new document. Below is an example where the content and metadata are copied to test2.txt from the folder.

import shutil
shutil.copy2("D:\test.txt", "D:folder\test2.txt")

Delete file

It is very easy to get rid of an object, if you know its name and exact location on the disk. The remove method from the previously mentioned os library will help with this task. All you need to do is give it the full address of the unwanted file as a parameter, remembering to include the os module first. Below is an example of how to use a Python script to remove the test.txt file in the root of the D drive.

import os
os.remove("D:\test.txt")

Obtaining file size

You can find out the exact size of any object on your hard drive using the standard function getsize from the os module, which returns the file size in bytes. Having imported the os library, you need to call the path class method. The argument here is the location of the document in computer memory. According to the results of getsize, the size of test.txt is 7289. The method print displays this value.

import os
print(os.path.getsize("D:\test.txt"))

7289

Another way to calculate the size of a file in Python is to open it with open and then call the seek function. Pass in an area from the beginning of the file to the end of the file as a parameter for the seek function. Finally, you should call the tell method with a reference to a text file and then send the result to print to be output to the console.

import os
with open("D:\test.txt") as file:
    file.seek(0, os.SEEK_END)
    print(file.tell())

7289

Renaming a file

It is possible to change the name of a document, not only with the help of the system, but also with the help of ready-to-use functions of the os module. The rename method that takes the original and new filename as parameters is good for this task. The following example shows how to rename a document test.txt, located at the root directory of drive D, to test1.txt.

import os
os.rename("D:\test.txt", "D:\test1.txt")

Similarly, you can rename a file in Python using the move method from the shutil module. By plugging in this library, all you have to do is pass the location and the new document name to the function. The program code demonstrating renaming test.txt to test1.txt is below.

import shutil
shutil.move("D:\test.txt", "D:test1.txt")

So, the main file operations in Python are handled by several built-in libraries, including os and shutil. The functions of these modules allow you to check for a file on disk, copy it in several different modes, and delete, rename, and display size.

Related Posts

LEAVE A COMMENT