In order to get working software sooner, I’ve decided to write the data to a csv file. This will allow us to get cracking on the photos without having to wait for the completed project. And for some people, a csv file will be enough. The database will just be extra complexity. But there is plenty of time to explore that route. For now, I just need to be able to write something to a csv file.
Write to csv File
ChatGPT gave me this code:
import csv
csv_filepath = "C:\\Users\\*****\\Desktop\\Team Turkey Run 2019\\TestOutput.csv"
with open(csv_filepath, 'w', newline='') as csvfile:
fieldnames = ['File Name', 'File Path', 'MD5 Hash']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'File Name': 'photo.jpg', 'File Path': 'file_path', 'MD5 Hash': 'md5_hash'})
Code Walkthrough
- The csv module implements classes to read and write tabular data in CSV format.
- This fie is opened in write mode -‘w’
- The open command will attempt to translate any newline characters into the appropriate character for the Operating System.
- When using the csv module, it is recommended to specify
newline = ''
. as csvfile
tells the code that the csv module will be handling the writing to file.- When writing a csv, it is required to tell it the
fieldnames
. For reading a file, this line is optional. - the csv.DictWriter operates like a regular writer but maps dictionaries onto output rows.
What is a csv File?
It is a Comma Separated Values files. This is very useful to us, because we can write to it as though it was just another text file. And yet the file can be opened in any spreadsheet application. In my case I use Libre Office Calc. But it works just the same in Excel or any other spreadsheet tool.
If you get a ‘Text Import’ screen when you open the file, just press OK. It will sort itself out.
If you make changes, you will need to ‘save as’ and change the file type to the default file type for your spreadsheet application. The csv format does not keep any formatting information. It only keeps text data.