Python Tutorial Part 7: Working with Files and File Handling

In this article, we'll explore how to work with files and perform file handling in Python.

Opening and Closing Files

To open a file in Python, you can use the open() function, specifying the file path and mode (e.g., read mode, write mode, append mode).

Example:

# Open a file in read mode
file = open("example.txt", "r")

# Read the contents of the file
content = file.read()
print(content)

# Close the file
file.close()

It's essential to close the file after you're done working with it to release system resources.

Reading from Files

Python provides various methods for reading from files, such as read(), readline(), and readlines().

Example:

# Open a file in read mode
file = open("example.txt", "r")

# Read the first line of the file
line1 = file.readline()
print(line1)

# Read all lines of the file into a list
lines = file.readlines()
print(lines)

# Close the file
file.close()

Writing to Files

You can write data to files in Python using the write() method.

Example:

# Open a file in write mode
file = open("output.txt", "w")

# Write data to the file
file.write("Hello, Python!\n")
file.write("This is a sample text file.\n")

# Close the file
file.close()

Conclusion

Working with files and performing file handling operations is a crucial aspect of Python programming. By mastering file operations, you can manipulate data stored in files efficiently and build powerful applications.

Previous Post Next Post