You are currently viewing File Handling in Python
Python | File Handling

File Handling in Python

File handling in Python refers to the ability to work with files such as reading from a file or writing to a file. Python provides several built-in functions and modules for handling files.

Here are the main topics that you should cover to get started with file handling in Python:
  1. Opening a file: Before you can work with a file in Python, you must first open it. You can open a file using the open() function. The syntax for opening a file is as follows:
file_object = open(filename, mode)

Here, filename is the name of the file that you want to open, and mode is the mode in which you want to open the file (read, write, append, etc.).

  1. Reading from a file: Once you have opened a file, you can read from it using the read() function. The read() the function reads the entire contents of the file and returns it as a string. Alternatively, you can use the readline() function to read one line at a time, or the readlines() function to read all the lines in the file and return them as a list.
  2. Writing to a file: To write to a file, you can use the write() function. The write() function writes a string to the file. You can also use the writelines() function to write a list of strings to the file.
  3. Closing a file: Once you are done working with a file, you should close it using the close() function. This frees up any system resources that were being used by the file.

Here is an example code that demonstrates file handling in Python:

# Opening a file
file_object = open("example.txt", "w")

# Writing to a file
file_object.write("Hello, world!\n")
file_object.writelines(["This is line 2\n", "This is line 3\n"])

# Closing the file
file_object.close()

# Opening the file for reading
file_object = open("example.txt", "r")

# Reading from the file
contents = file_object.read()
print(contents)

# Closing the file
file_object.close()

In the above code, we first open a file named example.txt in write mode using the open() function. We then write some text to the file using the write() function and a list of strings using the writelines() function. We then close the file using the close() function.

Next, we open the same file in read mode using the open() function, read the entire contents of the file using the read() function, and print the contents to the console. Finally, we close the file using the close() function.

Example

import threading

def worker():
    print("Thread started")
    # Perform some I/O-bound task
    print("Thread finished")

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

# Wait for all threads to finish
for t in threads:
    t.join()

print("All threads finished")

In this example, we define a function worker that performs some I/O-bound task. We then create five threads using the threading module, each of which calls the worker function. We store these threads in a list and start them using the start method. We then wait for all threads to finish using the join method, and print a message indicating that all threads have finished.

Note that due to the GIL, the threads will not execute in parallel on a single processor. However, the threads will still provide concurrency for I/O-bound tasks, as they can perform I/O operations simultaneously. If you need to perform CPU-bound tasks, you may want to consider using the multiprocessing module instead.

Usecase

Using multithreading in Python to improve the performance of a program that performs I/O-bound tasks:

import requests
import threading

def download(url):
    response = requests.get(url)
    with open(url.split('/')[-1], 'wb') as f:
        f.write(response.content)
    print(f"{url} downloaded")

urls = [
    'https://www.example.com/image1.jpg',
    'https://www.example.com/image2.jpg',
    'https://www.example.com/image3.jpg',
    'https://www.example.com/image4.jpg',
    'https://www.example.com/image5.jpg',
]

threads = []
for url in urls:
    t = threading.Thread(target=download, args=(url,))
    threads.append(t)
    t.start()

# Wait for all threads to finish
for t in threads:
    t.join()

print("All downloads finished")

In this example, we define a function download that downloads an image from a URL using the requests library and saves it to a file. We then create a list of URLs to download and create a thread for each URL using the threading module. We store these threads in a list and start them using the start method. We then wait for all threads to finish using the join method, and print a message indicating that all downloads have finished.

By using multithreading, we can download the images concurrently, which can greatly improve the performance of the program, especially if the images are large or the network connection is slow.

Leave a Reply