![]() |
VOOZH | about |
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.
Below are some examples by which we can understand File System Manipulation in Python:
Hello world
GeeksforGeeks
123
456
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
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!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!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!