blog image

Python : Files manipulation

Hello everyone, this is a small list of useful functions to manipulate files in Python, this is just the first part, i will make an other articles for APIs, Pandas etc..

  • Reading a File
    Reading the entire content of a file is a common task. You can achieve this using the read() method. The following example reads the content of the file “example.txt” and prints it:
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
  • Writing to a File
    To write text to a file, overwriting existing content, you can use the write() method. Here’s an example that writes “Hello, Python!” to the file “example.txt”:
with open('example.txt', 'w') as file:
    file.write('Hello, Python!')

  • Renaming a File
    Renaming a file is a common operation. You can use the os.rename() function to rename a file. Here’s an example that renames “old_file.txt” to “new_file.txt”::
import os
os.rename('old_file.txt', 'new_file.txt')
  • Appending to a File
    Appending text to the end of an existing file can be done using the a mode in the open() function. Let’s add the line “Append this line.” to “example.txt”:
with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')
  • Reading Lines into a List
    When you need to process a file line by line, you can read the lines into a list using the readlines() method. Here’s an example:

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)
  • Iterating Over Each Line in a File
    If you only need to process each line without storing them in a list, you can directly iterate over the file object. This example prints each line of “example.txt” after stripping any leading or trailing whitespace:

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())
  • Checking If a File Exists
    To avoid errors, it’s important to check if a file exists before performing operations on it. You can use the os.path.exists() function for this. Here’s an example:
import os
if os.path.exists('example.txt'):
    print('File exists.')
else:
    print('File does not exist.')
  • Writing Lists to a File
    To write each element of a list to a new line in a file, you can iterate over the list and write each item using the write() method. Let’s write the elements of the list lines to “example.txt”:

lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
    for line in lines:
        file.write(f'{line}\n')
  • Using With Blocks for Multiple Files
    Python’s with statement allows you to work with multiple files simultaneously. By combining multiple open() functions in a single with block, you can perform operations on different files. Here’s an example that reads from “source.txt” and writes to “destination.txt”:

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
    content = source.read()
    destination.write(content)
  • Deleting a File
    To safely delete a file, you can use the os.remove() function after checking if the file exists. Here’s an example:

import os
if os.path.exists('example.txt'):
    os.remove('example.txt')
    print('File deleted.')
else:
    print('File does not exist.')
  • Reading and Writing Binary Files
    Reading and writing in binary mode is useful for handling files like images and videos. You can specify the binary mode by using ‘rb’ for reading or ‘wb’ for writing. The following example demonstrates reading from a binary file and writing to a binary file:

# Reading a binary file
with open('image.jpg', 'rb') as file:
    content = file.read()

# Writing to a binary file
with open('copy.jpg', 'wb') as file:
    file.write(content)

  • Handling File Exceptions
    When working with files, it’s important to handle exceptions such as file not found errors. You can use a try-except block for this purpose. Here’s an example that handles a FileNotFoundError:

try:
    with open('nonexistent_file.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")
  • Copying a File
    To create a copy of a file, you can read the content of the source file and write it to a new file. Here’s an example that copies the contents of “source_data.txt” to “destination_data.txt”:

with open('source_data.txt', 'r') as source_file, open('destination_data.txt', 'w') as dest_file:
    content = source_file.read()
    dest_file.write(content)
  • Getting File Information
    You can obtain information about a file using the os.stat() function. This will provide details such as file size, permissions, and modification time. Here’s an example:

import os
file_info = os.stat('example.txt')
print(f"File size: {file_info.st_size} bytes")
print(f"Last modified: {file_info.st_mtime}")
  • Creating and Writing to Multiple Files
    If you need to create and write to multiple files dynamically, you can use loops and string formatting. Here’s an example that creates and writes to multiple files based on a list of file names:

file_names = ['file1.txt', 'file2.txt', 'file3.txt']
for name in file_names:
    with open(name, 'w') as file:
        file.write(f"Content for {name}")

  • Moving a File
    Moving a file from one location to another is a common operation. You can achieve this by using the shutil.move() function from the shutil module. Here’s an example that moves a file “old_location/file.txt” to “new_location/file.txt”:
import shutil
shutil.move('old_location/file.txt', 'new_location/file.txt')
  • Checking if a Path is a File or Directory
    You can determine if a given path points to a file or a directory using the os.path.isfile() and os.path.isdir() functions. Here’s an example that checks if a path corresponds to a file:
import os
path = 'example.txt'
if os.path.isfile(path):
    print(f'{path} is a file.')
else:
    print(f'{path} is not a file.')
  • Listing Files in a Directory
    To retrieve a list of files in a directory, you can use the os.listdir() function. Here’s an example that lists all files in the current directory:
import os
files = os.listdir('.')
print(files)
  • Creating and Writing to a Temporary File
    Temporary files are useful for storing data temporarily. You can create and write to a temporary file using the tempfile module. Here’s an example:
import tempfile
with tempfile.TemporaryFile(mode='w+') as temp_file:
    temp_file.write('Temporary data')
    temp_file.seek(0)
    print(temp_file.read())
  • Changing File Permissions
    You can modify file permissions using the os.chmod() function. Here’s an example that sets read and write permissions for the owner of a file:
import os
os.chmod('example.txt', 0o600)  # Owner has read and write permissions
  • Reading Specific Lines from a File
    If you only need to read specific lines from a file, you can use the linecache module. Here’s an example that reads the 3rd line from a file:
import linecache
line = linecache.getline('example.txt', 3)
print(f'Third line: {line}')

  • Copying a Directory
    To copy an entire directory along with its contents, you can use the shutil.copytree() function. This function creates a new directory and replicates the structure and files from the source directory. Here’s an example of copying a directory
import shutil
shutil.copytree('source_directory', 'destination_directory', dirs_exist_ok=True)
  • Searching for Files
    You can search for files matching a specific pattern or criteria within a directory using the glob module. This allows you to find files based on patterns like file extensions. Here’s an example that lists all Python files in a directory:
import glob
python_files = glob.glob('directory_path/*.py')
print(python_files)

These techniques provide a solid foundation for working with files in Python. Remember to adapt them to your specific needs and explore additional file manipulation functions offered by the Python standard library.

Leave a Reply

Your email address will not be published. Required fields are marked *