Working with Files

Opening a file with Python we need to close it as well.

# Open a new file object for writing only
myfile = open("/tmp/newfile.txt", "w")

# Use the write method to add data to the file
myfile.write("Here is my message.\n")

# The "\n" must be added to separate lines on the file
myfile.write("Here is my second message.")

# We must close out the file object in order to properly close the object
myfile.close()

Instead, we can use a with codeblock which will automatically handle closing the file once we're done with it.

with open("/tmp/newfile.txt", "r") as myfile:
    for line in myfile:
        print(line)

with open('/tmp/cars.txt', 'r') as cars:
    print(cars.read())

We can read all lines of a file into a list for easy use. We need to strip the newline as well.

def fileList(file):
    with open(file) as f:
        lines = f.readlines()
        clean = [ line.strip() for line in lines ]
    return clean

Last updated