Learning Python

16. Working with Files

16.1. Syntax

Attribuut Mode Description
“r” Read Default value. Opens a file for reading, error if the file does not exist
“a” Append Opens a file for appending, creates the file if it does not exist
“w” Write Opens a file for writing, creates the file if it does not exist
“x” Create Creates the specified file, returns an error if the file exists
“t” Text Default value. Text mode
“b” Binary Binary mode (e.g. images)
def main():
    f = open("demofile.txt")
def main():
    f = open("demofile.txt", "rt")

16.2. Reading files

def main():
    f = open("demofile.txt", "r")
    print(f.read())
def main():
    f = open("../demofile.txt", "r")
    print(f.read())

Read only part of the file

def main():
    f = open("demofile.txt", "r")
    print(f.read(5))

Read lines

def main():
    f = open("demofile.txt", "r")
    print(f.readline())
def main():
    f = open("demofile.txt", "r")
    print(f.readline())
    print(f.readline())
def main():
    f = open("demofile.txt", "r")
    for x in f:
        print(x)

16.3. Closing

def main():
    f = open("demofile.txt", "r")
    print(f.readline())
    f.close()

16.4. Writing files

open and read the file after the appending:

def main():
    f = open("demofile2.txt", "a")
    f.write("Now the file has more content!")
    f.close()

    #open and read the file after the appending:
    f = open("demofile2.txt", "r")
    print(f.read())

open and read the file after the appending

def main():
    f = open("demofile3.txt", "w")
    f.write("Woops! I have deleted the content!")
    f.close()

    f = open("demofile3.txt", "r")
    print(f.read())

16.5. Create a new file

“x”, “a”, “w”

def main():
    f = open("myfile.txt", "x")
def main():
    f = open("myfile.txt", "w")

16.6. Delete a file or folder

import os

def main():
    os.remove("demofile.txt")
import os

def main():
    if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
    else:
    print("The file does not exist")
import os

def main():
    os.rmdir("demodir")