When you edited your file counter script to write to a file, you probably added code similar to the one shown below:
# Above this would be your file counter code
# This code snippet assumes you're saving the count
# to a dictionary called `count`, e.g.:
count = {'': 8, '.csv': 2, '.md': 2, '.png': 11}
# New code that writes to a file
file_out = open("filecounts.txt", "w")
file_out.write(str(count))
file_out.close()
Note that you had to convert the count dictionary into a str() in order to write it to the file. If you don't do that, then Python will let you know by showing you a TypeError with clear instructions:
Traceback (most recent call last):
File "<input>", line 1, in <module>
file_out.write(count)
TypeError: write() argument must be str, not dict
If you did do the conversion, then you'll see a new file in your current folder that shows the expected content:
cat filecounts.txt
{'': 8, '.csv': 2, '.md': 2, '.png': 11}
Great! However, as soon as you run this script again, Python will overwrite all the existing content in your file. Also, if you want to display a longer dictionary, it'll become quite hard to read like this.
Appending To A File
You can open file objects in different modes. You've opened it in write mode ("w"), which always starts with a blank slate.
Instead, you can use the append mode ("a") to add new data to an existing file:
# 'append' mode
file_out = open("filecounts.txt", "a")
The rest of your code stays the same. If you now run your script a second time, you'll see that Python added a new dictionary at the end of the file:
cat hello.txt
{'': 8, '.csv': 2, '.md': 2, '.png': 11}{'': 8, '.csv': 2, '.md': 2, '.png': 11}
By only changing the mode that the file object operates under, you were able to keep adding new information on each run.
However, it looks messy and will be really hard to read after 20 runs if you leave the script as-is.
Formatting Your Output
So far, you've only stuck string representations of dictionaries one after another. This isn't a great way to read the logged output of your script, and it's even worse if you want to reuse the information for further processing.
You're only writing plain text to your file, so a quick way to improve the output would be to write a newline character at the end of each run. You can call the .write() method multiple times as long as the file is not yet closed:
# -- snip --
count = {'': 8, '.csv': 2, '.md': 2, '.png': 11}
file_out = open("filecounts.txt", "a")
file_out.write(str(count))
file_out.write("\n") # Include a line break
file_out.close()
In this example, you add a newline character ("\n"), which represents a line break, after you've written the string representation of your dictionary. That way, each run will write to a new line in your output file.
Since you're just working with text representation, you can apply any string formatting technique to the content you're writing to the file.
Summary: Python, Append to File
- File objects have different modes. If you want to add data at the end of a file object without overwriting the existing content, then you can use the append mode (
"a") when opening the file object. - Since you're just writing text to your files, you can format the text as you wish using string formatting techniques.
- In the next lesson, you'll use the persistent file memory that you created and access the data there.