Reading and Writing Text Files in Python
Reading and Writing Text Files
6
In Python, reading and writing text files is a fundamental concept that you need to know. A text file is a file that contains ASCII or Unicode characters, and each character represents a single byte.
Reading a text file primarily involves opening the file, reading its contents, and closing the file.
Here is an example:
with open('file.txt', 'r') as f: contents = f.read() print(contents)
In this example, we opened a file named file.txt
in read mode ('r'), read its contents using the read()
function, stored the contents in a variable named contents
, and printed the contents to the console.
Writing to a text file involves opening the file in write mode ('w'), writing or appending to the file, and then closing the file.
Here is an example:
with open('file.txt', 'w') as f: f.write('Hello, world!')
In this example, we opened a file named file.txt
in write mode ('w'), wrote the string 'Hello, world!' to the file using the write()
function, and then closed the file.
Overall, understanding how to read and write text files is essential for working with data and information in Python.
March 25, 2023