VOOZH about

URL: https://www.geeksforgeeks.org/python/file-system-manipulation-in-python/

⇱ File System Manipulation in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

File System Manipulation in Python

Last Updated : 23 Jul, 2025

File system manipulation in Python refers to the ability to perform various operations on files, such as creating, reading, writing, appending, renaming, and deleting. Python provides several built-in modules and functions that allow you to perform various file system operations. Python treats files differently based on whether they are text or binary. Each line of code in a text file includes a sequence of characters, terminated by an End of Line (EOL) character.

File System Manipulation in Python

Below are some examples by which we can understand File System Manipulation in Python:

  • Reading the File
  • Writing to the File
  • Creating a Directory and Writing File
  • Moving and Renaming Files

geeks.txt

Hello world
GeeksforGeeks
123
456

Reading the File

In this example, the below code opens a file named "geeks.txt" in read mode using the 'with' statement, ensuring proper file handling. It reads the content of the file and assigns it to the variable 'content'. Finally, it prints the content to the console.

Output

Hello world
GeeksforGeeks
123
456

Writing to the File

In this example, below code opens a file named "geeks.txt" in write mode using the 'with' statement for proper file handling. It then writes the string "Python is amazing!" to the file, effectively replacing any previous content with this new text.

Output (geeks.txt)

Python is amazing!

Creating Directory & Writing File

In this example, below code imports the 'os' module for operating system functionality. It creates a directory named "my_directory" using 'os.mkdir()'. Then, it changes the current working directory to "my_directory" using 'os.chdir()'. Inside the directory, it creates a file named "my_file.txt" and writes "Hello, world!" to it.

Output

['my_file.txt']

my_directory/my_file.txt:

Hello, world!

Moving and Renaming Files

In this example, below code imports the 'shutil' and 'os' modules for file operations. It creates a file named "my_file.txt" with the content "Hello, world!". Then, it moves and renames the file to "new_directory/my_new_file.txt".

Output

['my_file.txt']

my_file.txt:

Hello, world!
Comment