Data Files in Python
In Python, a data file is a file that stores data. The data can be in many forms, such as text, binary, json, csv, etc. Python provides built-in functions to read from and write to data files.
1. Text Files
These are the most common file that you’ll come across. They can be opened in a standard text editor. Here’s an example of how you can write to a text file:
# Writing to a file with open('myfile.txt', 'w') as f: f.write('Hello, world!')
And reading from a text file:
# Reading from a file with open('myfile.txt', 'r') as f: content = f.read() print(content) # Output: Hello, world!
2. Binary Files
These are files that are not in a human-readable format. Here’s an example of writing binary data to a file:
# Writing binary data to a file with open('myfile.bin', 'wb') as f: f.write(b'\x3c\x2f\x66\x6f\x6f\x3e') # Writes '' in ASCII
And reading from a binary file:
# Reading binary data from a file with open('myfile.bin', 'rb') as f: content = f.read() print(content) # Output: b''
3. CSV (Comma-Separated Values) Files
These are a type of flat file which uses specific structuring to arrange tabular data. Python provides a csv module to deal with CSV files. Here’s an example of writing to a CSV file:
import csv # Writing to a CSV file with open('myfile.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(["SN", "Name", "Contribution"]) writer.writerow([1, "Linus Torvalds", "Linux Kernel"]) writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
And reading from a CSV file:
import csv # Reading from a CSV file with open('myfile.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row)
4. JSON (JavaScript Object Notation) Files
These are a popular data exchange format and are human readable. The json module in Python provides a method called json.dump() for writing data to JSON files. Similarly, we can use json.load() to read data from a JSON file.
import json # Writing to a JSON file data = { "Name": "Zophie", "Species": "cat", "age": 7 } with open('data.json', 'w') as f: json.dump(data, f)
And reading from a JSON file:
import json # Reading from a JSON file with open('data.json', 'r') as f: data = json.load(f) print(data) # Output: {'Name': 'Zophie', 'Species': 'cat', 'age': 7}
Please remember to replace ‘myfile.txt’, ‘myfile.bin’, ‘myfile.csv’, and ‘data.json’ with the path to your own file. If you don’t provide a full path, Python will look for the file in the same directory as the script you’re running.