File R/W

Read from a file

Assuming a file called some_file.txt already exists in the same folder as this Python script, and the contents of that file are hello, world!. The following python script will:

  • open the file,

  • read its contents (as a str) into a variable called contents,

  • close the file (by virtue of leaving the with context),

  • then print out hello, world!.

with open("some_file.txt", "r") as f:
    contents = f.read()

print(contents)

Read multiple lines from a file

with open("read_mult_lines.txt", "r") as f:
    for line in f:
        print(line.strip())

If you do not use the .strip() method, every line will be read in with the \n character at the end. .strip() gets rid of it.

Note

To be a bit more explicit, use the .readlines() method in your loop.

for line in f.readlines():
    pass

Write to a file

The write flag "w" will overwrite the entire file’s contents.

with open("write_to_file.txt", "w") as f:
    f.write("Hello. I am writing to a file!\n")
    f.write("Next line!")

Note

The .write() method does not automatically add a new line at the end. If you want something on a new line, the new-line character (\n) must be manually placed somewhere.

Append to a file

The append flag, "a" will allow you to write to the end of a file, without overwriting its contents.

with open("append_to_file.txt", "a") as f:
    f.write("hello\n")

Note

Remember the .write() method doesn’t add a new-line character for you. See Write to a file note for more info.

Write multiple lines to a file

If we had a list of marks we wanted saved permenantly into a file, we could use this script:

marks = [56, 87, 34, 76, 87, 88]

with open("marks.txt", "w") as f:
    for mark in marks:
        f.write(f"{mark}\n")

Just use a loop to call the .write() method multiple times.

Write JSON data to a file

JSON is a web-standard structure for transporting data back and forth between clients (a web browser) and web-servers. Python comes with a very useful json library that can help write information contained in dictionaries to files extremely easily. All you need is a Python dictionary and the json.dump() function.

import json

data = {
    "name": "Jeff",
    "marks": [77, 88, 99],
    "happy": True
}

with open("jeff_info.json", "w") as f:
    json.dump(data, f, indent=4)

The use of the indent=4 key-word argument is optional, however, it makes the output much nicer to read. This will write to a file called jeff_info.json the following:

{
    "name": "Jeff",
    "marks": [
        77,
        88,
        99
    ],
    "happy": true
}

Notice that the JSON is nearly identical to the Python dictionary.

Load JSON data from a file

In order for the json.load() function to operate correctly, the file it is attempting to read must be 100% valid JSON, or there will be errors while calling the function.

with open("jeff_info.json", "r") as f:
    data = json.load(f)

print(data)  # just a regular, old-fashioned, python dictionary

Changing the contents of a file

To change the contents of a file, you must not only load the contents of the file into your Python progam and change the values, you must also then write back to the file for the changes to actually be saved.