Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Links | Search | Bio |

Guide to Python (University at Buffalo Version)


Chapter 6: Working With Files (I/O)

File Input/Output (I/O)

Python provides many File I/O functions for working with files.

Managing a File Using the open(), read(), and close() Functions

To work with a file using Python you need to open the file using the open() function. To destroy a file resource use the close() function.

Reading a File Using the Python read() Function

You can use the read() function to read the file.

# read_all.py
f = open("cis151_io.txt", "r")
print(f.read())
Figure 6-1: The fopen(), fscanf() and fclose() Functions
1,January,31

2,February,28

3,March,31

4,April,30

5,May,31

6,June,30

7,July,31

8,August,31

9,September,30

10,October,31

11,November,30

12,December,31
Figure 6-2: The fopen(), fscanf() and fclose() Output

Installing pandas, prettytable, and tabulate Libraries

C:\Windows\System32>cd C:\Users\user\AppData\Local\Programs\Python\Python312

C:\Users\user\AppData\Local\Programs\Python\Python312>python --version
Python 3.12.8

C:\Users\user\AppData\Local\Programs\Python\Python312>cd Scripts

C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts>pip install pandas
Collecting pandas
  Downloading pandas-2.2.3-cp312-cp312-win_amd64.whl.metadata (19 kB)
Collecting numpy>=1.26.0 (from pandas)
  Downloading numpy-2.2.1-cp312-cp312-win_amd64.whl.metadata (60 kB)
Collecting python-dateutil>=2.8.2 (from pandas)
  Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB)
Collecting pytz>=2020.1 (from pandas)
  Downloading pytz-2024.2-py2.py3-none-any.whl.metadata (22 kB)
Collecting tzdata>=2022.7 (from pandas)
  Downloading tzdata-2024.2-py2.py3-none-any.whl.metadata (1.4 kB)
Collecting six>=1.5 (from python-dateutil>=2.8.2->pandas)
  Downloading six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB)
Downloading pandas-2.2.3-cp312-cp312-win_amd64.whl (11.5 MB)
   ---------------------------------------- 11.5/11.5 MB 36.0 MB/s eta 0:00:00
Downloading numpy-2.2.1-cp312-cp312-win_amd64.whl (12.6 MB)
   ---------------------------------------- 12.6/12.6 MB 41.6 MB/s eta 0:00:00
Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
Downloading pytz-2024.2-py2.py3-none-any.whl (508 kB)
Downloading tzdata-2024.2-py2.py3-none-any.whl (346 kB)
Downloading six-1.17.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: pytz, tzdata, six, numpy, python-dateutil, pandas
  WARNING: The scripts f2py.exe and numpy-config.exe are installed in
  'C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts' which is not 
  on PATH. Consider adding this directory to PATH or, if you prefer to suppress 
  this warning, use --no-warn-script-location.
Successfully installed numpy-2.2.1 pandas-2.2.3 python-dateutil-2.9.0.post0 
pytz-2024.2 six-1.17.0 tzdata-2024.2

C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts>pip install tabulate
Collecting tabulate
  Using cached tabulate-0.9.0-py3-none-any.whl.metadata (34 kB)
Using cached tabulate-0.9.0-py3-none-any.whl (35 kB)
Installing collected packages: tabulate
Successfully installed tabulate-0.9.0

C:\Users\jimge\AppData\Local\Programs\Python\Python312\Scripts>pip install prettytable
Collecting prettytable
Downloading prettytable-3.14.0-py3-none-any.whl (31 kB)
Installing collected packages: prettytable
Successfully installed prettytable-3.14.0

C:\Users\jimge\AppData\Local\Programs\Python\Python312\Scripts>
Figure 6-p: Windows: Install pandas, prettytable, and tabulate Output

Reading a CSV File Using the Python the pandas Library

You can use the read_csv() function of the pandas to read a file one line at a time.

import pandas as pd
# readCSV.py2

# Replace 'your_file.csv' with the path to your CSV file
df = pd.read_csv('subscribers.csv')

# Display the first few rows of the dataframe
print(df.head())
Figure 6-3: The pandas read() Function
   Jim Gerland     "gerlanjr@buffalostate.edu"   "(716)123-4567"
0  Jim Gerland            "gerlnd@buffalo.edu"   "(716)456-7890"
1  Jim Gerland   "jim.gerland@thegerlands.org"   "(716)789-1234"
Figure 6-4: The pandas read() Output

Reading a File Using the Python readline() Function

You can use the <open() function to read a file one line at a time.

# read_all.py
f = open("cis151_io.txt", "r")

i = 1
for l in f:
    n = l.rstrip("\r\n")
    if (n != ""):
        print("Line ", i, ": ", n)
        i += 1
Figure 6-5: The open() Function
Line  1 :  1,January,31
Line  2 :  2,February,28
Line  3 :  3,March,31
Line  4 :  4,April,30
Line  5 :  5,May,31
Line  6 :  6,June,30
Line  7 :  7,July,31
Line  8 :  8,August,31
Line  9 :  9,September,30
Line  10 :  10,October,31
Line  11 :  11,November,30
Line  12 :  12,December,31
Figure 6-6: The open() Output

Writing a File Using the Python write() Function

You can use the "w" to write to a file or the "a+" file mode on the open() function to append to a file. You can then use the write() function to write to that file.

# write.py

f = open("myLines.txt", "w")

for i in range(5):
    l = "This is line: " + str(i)
    f.write(l)
    print(l, " written")
Figure 6-7: The write() Function
This is line: 0  written
This is line: 1  written
This is line: 2  written
This is line: 3  written
This is line: 4  written
Figure 6-8: The write() Output

Formatting Output

You can use the f (F-String) method when outputing data.

# format.py

textbookPrice = 69.95
    print(f"The textbok costs ${textbookPrice:.2f}")
Figure 6-9: Using f to Format Data
The textbok costs $69.95
Figure 6-10: Formatted Output

Handling Exceptions

You can use a try/except block to handle error (exceptions) when yiur program is running. An exception can happen if a variable is not defined, or a file cannot be opened, or a database connection is not successful, etc.. See the Geeks For Geeks exception types page for more information.

# exception.py
"""
    File: Sample try/except code
    Author: Jim Gerland
    Date: 12/15/2024
"""

try:
    f = open("subscribers.csv")
    try:
      o = open("newsubscribers.txt", "+a")
      o.write("New subscriber")
    except OSError as P:
      print("Error occured when trying to write to the file")
      if hasattr(P, "message"):
        print(P.message)
      else:
        print(P)
    finally:
      f.close()
except OSError as F:
    print("Error occured when trying to open the file")
      if hasattr(F, "message"):
        print(F.message)
      else:
    print(F.message)
Figure 6-11: Formatting Output

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2025 Jim Gerland