Files in python
In Python, you can use the built-in open() function to work with files. The open() function allows you to read from and write to files in various modes. Here's how you can use it to read from and write to files:
To read from a file, you need to open it in read mode using the "r" flag. You can use the read() method to read the entire content of the file, or you can use iteration to read line by line.
# Reading the entire content of the file
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("sample.txt", "r") as file:
for line in file:
print(line.strip()) # Strip newline characters
To write to a file, you need to open it in write mode using the "w" flag. If the file already exists, opening it in write mode will overwrite its content. If it doesn't exist, a new file will be created.
# Writing to a file
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.\n")
# Appending to a file
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
You can also open a file in both read and write mode using the "r+" or "w+" flags. Be cautious when using "w+" as it truncates the file (empties it) if it already exists.
# Reading and writing to a file
with open("data.txt", "r+") as file:
content = file.read()
file.write("New data added.")
file.seek(0) # Move cursor back to the beginning
updated_content = file.read()
print(updated_content)
You can open various types of files, such as text files, CSV files, JSON files, etc., using the appropriate mode and then process their content accordingly. For example, you can use the "csv" module to read and write CSV files and the "json" module to read and write JSON files.
Remember to use the "with" statement when working with files. It automatically takes care of closing the file after you're done, ensuring that resources are properly managed.
Working with files using the "open()" function allows you to read and write data efficiently, making it possible to interact with external files and store or retrieve data for your programs.