10 Python File System Methods You Should Know


Collaborating with the file organization is a routine undertaking in coding, and Python equips a bountiful collection of instruments to connect with files and folders. In this discourse, we'll unfold ten Python file management functions that you ought to comprehend to streamline your coding endeavors. We'll escort you through each function, illustrating its operations in uncomplicated steps.

Initiating and concluding a file

Let’s assume example.txt contains the text "Hello, World!".

Example

doc = open('example.txt', 'r')
contents = doc.read()
doc.close()
print(contents) 

Output

Hello, World!

The open() operation accepts two parameters: the file trajectory and the file mode. In this illustration, the mode is 'r', which signifies the file is initiated for scrutinizing. Don't neglect to conclude the file employing the close() method when you're done utilizing it.

Scrutinizing a file

To scrutinize the entire substance of a file, employ the read() method on a file entity −

Example

with open('example.txt', 'r') as doc:
   substance = doc.read()
print(substance)

Output

Hello, World!

The with clause ensures that the file is automatically concluded when the block is exited. The substance variable will contain the file's substance as a string.

Inscribing to a file

To inscribe data to a file, open it in write mode ('w') and employ the write() method −

Example

with open('output.txt', 'w') as doc:
doc.write('Hello, World!')

Output

Hello, World!

This code part shapes an unused record named output.txt (or overwrites it if it already exists) and inscribes the string 'Hello, World!' into it.

Appending to a file

To append data to an existing file, open it in append mode ('a') −

Example

with open('example.txt', 'a') as doc:
doc.write('\nAppended text.')

Output

Hello, World!

This code fragment initiates the example.txt file and appends the string '\nAppended text.' into it.

Scrutinizing a file line by line

To scrutinize a file line by line, employ a for loop to iterate over the file entity −

Example

with open('example.txt', 'r') as doc:
for row in doc:
print(row.strip())

Output

Hello, World!

This code fragment scrutinizes the example.txt file line by line and prints each row without leading or trailing whitespace.

Forming a folder

To form a new directory, employ the os.mkdir() operation −

Example

import os
os.mkdir('new_folder')

Output

The directory "new_folder" was created successfully.

This code fragment imports the os module and forms a new folder termed new_folder.

Eradicating a folder

To eradicate an empty folder, employ the os.rmdir() operation −

Example

import os
os.rmdir('empty_folder')

Output

The directory "empty_folder" was removed successfully.

This code fragment eradicates the empty_folder. Take note that it only functions if the folder is devoid of content.

Listing files and folders

To list the files and folders in a directory, employ the os.listdir() operation −

Example

import os
docs_and_folders = os.listdir('some_folder')

Output

['file1.txt', 'file2.txt', 'another_folder', 'yet_another_folder']

This code fragment yields a list of file and folder names in the some_folder

Verifying if a file or folder exists

To verify if a file or folder exists, employ the os.path.exists() operation −

Example

import os
if os.path.exists('example.txt'):
   print('The file exists')
else:
   print('The file does not exist')

Output

The file exists

This code fragment verifies if the example.txt file exists and prints a corresponding declaration. The os.path.exists() operation returns True if the file or folder exists and False otherwise.

Renaming a file or folder

To rename a file or folder, employ the os.rename() operation −

Example

import os
os.rename('old_designation.txt', 'new_designation.txt')
print(os.listdir())

This code snippet alters the file old_designation.txt to new_designation.txt. It can also be harnessed to transport a file or folder to a fresh locale.

Output

['new_designation.txt', 'another_file.txt', 'yet_another_file.txt']

Conclusion

These ten Python file management functions are crucial implements for interacting with files and folders in your coding ventures. By acquainting yourself with these functions and integrating them into your code, you can economize time and amplify your Python competencies. Don't falter to refer to the Python documentation for more data on these functions and to probe additional file organization functionality.

Updated on: 09-Aug-2023

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements