Wednesday, September 4, 2024

PYTHON - FILE HANDLING

 File Handling in python


File handling in Python allows you to work with files on your computer's filesystem. You can create, read, write, and manipulate files using various methods and functions provided by Python's built-in modules. Here, I'll explain the basic concepts of file handling in Python and provide a sample program for each operation.


Opening and Closing Files:
To work with a file, you must first open it using the open() function. It takes two arguments: the filename and the mode in which you want to open the file (e.g., read, write, append, etc.). After working with the file, you should close it using the close() method to free up system resources.

Sample program to open and close a file:

# Opening a file in write mode
file = open("sample.txt", "w")

# Writing data to the file
file.write("Hello, World!")

# Closing the file
file.close()


Reading from a File:

You can read the contents of a file using the read() method or by iterating over the file line by line using a loop.

Sample program to read from a file:

# Opening a file in read mode
file = open("sample.txt", "r")

# Reading the entire content
content = file.read()
print(content)

# Closing the file
file.close()


Writing to a File:
Open it in write mode ("w") to write data to a file. You can use the write() method to add content to the file. Be cautious, as opening a file in write mode will overwrite its existing content.

Sample program to write to a file:

# Opening a file in write mode
file = open("sample.txt", "w")

# Writing data to the file
file.write("Hello, World!")

# Closing the file
file.close()

Appending to a File:
If you want to add content to a file without overwriting the existing content, open the file in append mode ("a").

Sample program to append to a file:

# Opening a file in append mode
file = open("sample.txt", "a")

# Appending data to the file
file.write("\nThis is a new line.")

# Closing the file
file.close()

No comments:

Post a Comment