Reading from and writing to files in Python is straightforward and can be accomplished using the built-in open() function. Here's a basic guide to help you get started:
Reading from a File
- Open the File: Use
open()to open the file. You can specify the mode as'r'for reading. - Read the File: Use methods like
read(),readline(), orreadlines()to read the file contents. - Close the File: Always close the file using
close()to free up system resources.
Writing to a File
- Open the File: Use
open()with mode'w'for writing,'a'for appending, or'w+'for reading and writing. - Write to the File: Use methods like
write()orwritelines()to write data to the file. - Close the File: Close the file using
close().
Here's an example of writing to a file:
# Open the file in write mode with open('example.txt', 'w') as file: # Write some text to the file file.write('Hello, world!') # If you want to append to the file, use 'a' mode with open('example.txt', 'a') as file: # Append some text to the file file.write('\nAppended text.')
Using with Statement
Using the with statement is a good practice as it automatically closes the file for you, even if an exception occurs.
Full Example: Reading and Writing
Here’s a full example demonstrating both reading from and writing to a file:
# Write to the file with open('example.txt', 'w') as file: file.write('Hello, world!\n') file.write('This is a test file.\n') # Read from the file with open('example.txt', 'r') as file: contents = file.read() print(contents)
Common File Modes
'r': Read (default mode). Opens the file for reading.'w': Write. Opens the file for writing (creates a new file or truncates the existing file).'a': Append. Opens the file for appending (creates a new file if it doesn't exist).'r+': Read and write. Opens the file for both reading and writing.'w+': Write and read. Opens the file for writing and reading (creates a new file or truncates the existing file).'a+': Append and read. Opens the file for appending and reading (creates a new file if it doesn't exist).
By using these simple techniques, you can easily read from and write to files in Python.
Comments
Post a Comment