Python file handling is a powerful tool that allows you to read, write, and manipulate files.
Opening a file
To open a file in Python, you use the open() function. The open() function takes two arguments: the path to the file and the mode in which to open the file.
The mode specifies how the file will be opened. The following are some common modes:
Example:
Python
# Open the file "myfile.txt" for reading
f = open("myfile.txt", "r")
Reading from a file
To read from a file, you can use the read() method. The read() method returns the contents of the file as a string.
Example:
Python
# Read the contents of the file "myfile.txt"
contents = f.read()
# Print the contents of the file
print(contents)
Writing to a file
To write to a file, you can use the write() method. The write() method takes a string as an argument and writes it to the file.
Example:
Python
# Open the file "myfile.txt" for writing
f = open("myfile.txt", "w")
# Write the string "Hello, world!" to the file
f.write("Hello, world!")
# Close the file
f.close()
Appending to a file
To append to a file, you can use the append() method. The append() method takes a string as an argument and appends it to the end of the file.
Example:
Python
# Open the file "myfile.txt" for appending
f = open("myfile.txt", "a")
# Append the string "This is a new line of text." to the file
f.write("This is a new line of text.")
# Close the file
f.close()
Closing a file
Once you have finished reading from or writing to a file, you should close it. This will release the file resources and ensure that the data in the file is saved.
Example:
Python
# Open the file "myfile.txt" for reading
f = open("myfile.txt", "r")
# Read the contents of the file
contents = f.read()
# Close the file
f.close()
Conclusion
Python file handling is a powerful tool that allows you to read, write, and manipulate files. By understanding how to use file handling, you can write more efficient and robust code.
Please support us by disabling your ad blocker for this website.
We rely on advertising revenue to keep the lights on and content free.
Thank you for understanding ❤️