Ahoy, Python neophyte! We're about to embark on a journey into the realm of dataโmore specifically, files. Just as a bard collects stories in his notebook, we, the programmers, often need to collect and store our data in files. Here's how you can master the art of file manipulation in Python.
File I/O operations
In Python, working with files is like having a chat with an old parchmentโyou open the chat (file), read or write your messages (data), and then close the chat (file).
Here's an example:
# Open the chat (file)
file = open('myParchment.txt', 'w')
# Write your messages (data)
file.write('Hello, parchment!')
# Close the chat (file)
file.close()
Remember that 'w'
here stands for write mode. If you want to read from a file, use 'r'
. And if you wish to do both, use 'r+'
.
Working with different file formats (.txt, .csv, .json)
Like conversing in different languages, each file format has its quirks.
.txt Files: These are the easiest to work with. It's as simple as:
file = open('myParchment.txt', 'r') text = file.read() # Reads the entire file file.close()
.csv Files: Python has a
csv
module for these, making your life simpler than a hobbit's in the Shire:import csv with open('myScroll.csv', 'r') as file: scrolls = csv.reader(file) for scroll in scrolls: print(scroll)
.json Files: And then there's the magical
json
module for the ever-popular .json files:import json with open('myBook.json', 'r') as file: book = json.load(file) print(book['title'])
Notice that we're using a with
statement to open the files here. This is a neat little Python trickโit automatically closes the file once you're done with it.
Now you're ready to tell your own stories in Python, whether it be on parchment, a scroll, or in a book! But remember, with great power comes great responsibility. Always handle your data with care, young Pythonist!