File Input/Output#

  • The built-in function open is used to open files on the filesystem

f = open(file_name, mode)
  • file_name - just the file name in string format if the file is in the current working directory

    • Full or relative path needs to be specified, otherwise

  • mode - an optional string input that specifies the mode in which the file is opened

    • Default is to open the file as a text file in read-only mode

  • open function has other parameters with default values

  • The output f is a file object which has the following methods/attributes:

    • close/closed

      • To close and check status of the file object, respectively

    • read, readline, readlines

      • To read data from the file

    • write, writelines

      • To write data to the file

    • seek, tell

      • To navigate through the file

Usage of open Function#

  • Current working directory (CWD) is the directory from which the Python interpreter is invoked

    • Use the os module to identify if unsure

import os
os.getcwd()
'/home/runner/work/EngineeringComputations/EngineeringComputations/engineering_computations'
  • If the file is in the CWD

f = open("numbers.txt")
  • If no such file exists, you get an exception

  • Using relative paths

    • Sub-director within the CWD

    f = open("SubDir/numbers.txt")
    
    • Parent directory to the CWD

    f = open("../numbers.txt")
    
    • Parent of the parent directory to the CWD

    f = open("../../numbers.txt")
    
  • Using absolute paths

    • On macOS/Linux

    f = open("/home/jane/python/numbers.txt")
    
    • On Windows with backslashes

    f = open("c:\\Users\\Jane\\python\\numbers.txt")
    
    • On Windows with forward slashes

    f = open("C:/Users/Jane/python/numbers.txt")
    

Input Parameter mode#

  • The mode string can be upto 3 characters long

  • The first character determines whether the file is opened for reading or writing

Character

Meaning

'r'

Opens the files for reading in text mode (default)

'w'

Opens the file for writing and removes the current contents. Creates a new file if the file does not exist.

'x'

Creates a new file and opens it for writing; raises an error if the file already exists

'a'

Same as 'w' but appends to the current contents instead of overwriting

  • The second charater, when used, determines if the file should be both readable and writeable

Character

Meaning

'+'

Adding this with read mode (like so 'r+') makes the file writeable. With the other three modes, the file becomes readable.

  • The third character, when used, determines whether the file contents are to be considered textual or binary data

Character

Meaning

't'

Text mode (default)

'b'

Binary mode

# Example
f = open("./numbers.txt", 'r+b')
  • The file if exists will be opened in binary mode with read and write permissions

  • An error will be seen if the file does not exist

Reading Files#

  • File reading methods available on the file object (the output of open function):

    • read()

    • readlines()

    • readline()

  • read()

    • Reads the entire file from the current location and returns a string

    • Not recommended for large files

  • readlines()

    • Reads the entire file from the current location and returns a list of strings

    • Each string in the list is a line

  • readline()

    • Reads a single line from the current location and retuns a string

  • tell()

    • Tells the current location

  • seek(offset, whence)

    • Moves the current location by offset bytes from a reference location

    • whence specifies the reference location

      • 0 (default) - beginning of the file

      • 1 - current location

      • 2 - end of the file

  • close()

    • Closes the opened file

    • All opened files must be closed after the desired file operations to free up resources

    • Once closed, the file should be reopened to work with it again

  • Code to open and read data from a file

# Open a file
f = open("numbers.txt")

# Do some stuff – read a line
data1 = f.readline()

# Do more stuff – read rest of the file
data2 = f.read()

# Close the file object
f.close()

print(data1)
print(data2)
20

75
123
92084
1
856
appended line 1
appended line 2
appended line 3
appended line 4
  • The file is opened in read-only mode 'r'; use of write methods write or writelines will cause an exception

  • A safer way to open and work with files is to use the with statement

    • with is a compound statement that automates error handling for a code block

    • with ensures that the file is closed after the accompanying indented code block is executed

# Open numbers.txt
with open("./numbers.txt") as f:
    # Do some stuff – read a line
    data1 = f.readline()

    # Do more stuff – read the rest
    data2 = f.read()

# Code block ends - file closed by the with statement

print(data1)
print(data2)
20

75
123
92084
1
856
appended line 1
appended line 2
appended line 3
appended line 4
  • A simple and efficient way to read the file one line at a time

    • Use the iterable nature of the file object

with open("./numbers.txt", 'r') as file:
    for line in file:
        print(line, end="")
20
75
123
92084
1
856
appended line 1
appended line 2
appended line 3
appended line 4

Writing Files#

  • write(string)

    • Writes the input string parameter to the file and moves the current position

with open("./numbers.txt", 'a+') as file:
    # Add a few lines to the end of the file
    for i in range(4):
        file.write(f"appended line {i+1}\n")

    # Read the modified file
    file.seek(0)
    text = file.read()

print(text)
print('Done!')
20
75
123
92084
1
856
appended line 1
appended line 2
appended line 3
appended line 4
appended line 1
appended line 2
appended line 3
appended line 4

Done!
  • writelines(sequence_of_strings)

    • Writes each string in the input sequence (list, tuple, or, dictionary) to the file

with open("newfile.txt", 'w+') as file:
    # Create a list of strings
    listOfStrs = []
    for i in range(4):
        listOfStrs.append(f"line {i+1}\n")
        
    # Write the list to the file
    file.writelines(listOfStrs)

    # Write a tuple
    file.writelines(('1\n', '2\n', '3\n'))

    # Write keys of a dictionary
    file.writelines({'x\n' : 10, 'y\n' : 20, 'z\n' : 30})

    # Read the modified file
    file.seek(0)
    text = file.read()

print(text)
line 1
line 2
line 3
line 4
1
2
3
x
y
z