Skip to main content
Published on

Files (Write and Read) in Python

Share:

Introduction

Working with files is an essential skill in programming. In Python, file manipulation is simple yet powerful, allowing you to read, write, and modify file contents efficiently.

How to Work with Files in Python

Opening and Closing Files

Use open(file, mode) to open a file. The mode parameter determines the operation: 'w' for writing and 'r' for reading. It is crucial to close the file after use with close(file).

Writing to Files

To write to a file, open it in 'w' mode. Any existing content will be replaced. Use write(text) to write to the file.

writeFile = open('Files-Write-and-Read.txt', 'w')
writeFile.write('I am writing on the first line of this file.\n')
writeFile.write('Now I am writing on the second line.')
writeFile.close()

Reading Files

To read a file, open it in 'r' mode. The read() method is used to read all the content.

readFile = open('Files-Write-and-Read.txt', 'r')
print(readFile.read())
readFile.close()

Best Practices

  • Always close files after use to avoid memory leaks or file conflicts.
  • Use context managers (with) to automatically manage file closing.

Conclusion

Manipulating files in Python is a straightforward and efficient process. Understanding these basic operations opens the door to more complex work, such as data analysis and file management.

Happy coding!