Files input and output

Files input and output

Python provides several ways to handle input and output of files. Here are some commonly used methods:

Reading a File

To read the contents of a file, you can use the open() function in Python, which returns a file object. Here’s an example:

pythonCopy codewith open('filename.txt', 'r') as file:
    contents = file.read()
    print(contents)

In the above example, filename.txt is the name of the file you want to read, and 'r' specifies that you want to read the file. The with statement is used to automatically close the file when you’re done with it.

Writing to a File

To write data to a file, you can open the file in 'w' (write) mode using the open() function. Here’s an example:

pythonCopy codewith open('filename.txt', 'w') as file:
    file.write('Hello, world!')

In the above example, filename.txt is the name of the file you want to write to. The 'w' mode indicates that you want to write to the file. The write() method is used to write data to the file.

Appending to a File

To append data to an existing file, you can open the file in 'a' (append) mode using the open() function. Here’s an example:

pythonCopy codewith open('filename.txt', 'a') as file:
    file.write('\nHello again!')

In the above example, the '\n' character is used to insert a new line before the appended text.

Closing a File

It’s important to remember to close a file when you’re done with it to free up system resources. The with statement automatically closes the file when it’s done, but if you’re not using the with statement, you can close the file manually using the close() method:

pythonCopy codefile = open('filename.txt', 'r')
contents = file.read()
file.close()

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Input output
Pickle in python

Get industry recognized certification – Contact us

keyboard_arrow_up