Fundamentals 11 min read

Master Python File I/O, Dialogs, and Exception Handling in One Guide

This guide walks you through opening, reading, writing, and closing files in Python, detecting file existence, using file dialogs, fetching web data, handling exceptions, raising custom errors, and performing binary I/O with pickle, complete with code examples and practical tips.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Python File I/O, Dialogs, and Exception Handling in One Guide

1. Open a File

Use the built‑in open(filename, mode) function, where filename is the path and mode specifies how the file is opened (e.g., "r" for reading, "w" for writing).

<code>input = open(r"/home/usr/test.txt", "r")
</code>

2. Write Data

2.1 File Object

Calling open returns a _io.TextIOWrapper instance that provides methods such as write() , read() , and close() .

2.2 Detect File Existence

Before writing, check whether a file already exists to avoid accidental overwrites:

<code>import os.path
if os.path.isfile("presidents.txt"):
    print("文件已经存在")
</code>

2.3 Read All Data

Use read() or readlines() for small files; for large files, iterate line by line:

<code>for line in infield:
    # process each line
</code>

Example that copies the contents of one file to another while counting lines and characters:

<code>import os.path, sys

def main():
    f1 = input("请输入原文件:").strip()
    f2 = input("请输入目标文件:").strip()
    if os.path.isfile(f2):
        print(f2 + "已经存在了")
        sys.exit()
    infile = open(f1, "r")
    outfile = open(f2, "w")
    countLines = countChars = 0
    for line in infile:
        countLines += 1
        countChars += len(line)
        outfile.write(line)
    print(countLines, "lines and", countChars, "chars copied")
    infile.close()
    outfile.close()

main()
</code>

2.4 Write Numbers

Convert numbers to strings before writing them with write() .

3. File Dialogs

The tkinter.filedialog module provides askopenfilename() and asksaveasfilename() for opening and saving files through a GUI dialog.

<code>from tkinter.filedialog import askopenfilename, asksaveasfilename

filenameforReading = askopenfilename()
print("you can read from" + filenameforReading)

filenameforWriting = asksaveasfilename()
print("you can write data to " + filenameforWriting)
</code>

4. Fetch Data from a Website

Use urllib.request.urlopen() to retrieve data from a URL, then decode the bytes to a string.

<code>import urllib.request

def main():
    url = input("输入网址: ").strip()  # e.g., https://www.baidu.com
    infile = urllib.request.urlopen(url)
    s = infile.read().decode()
    counts = countLetters(s.lower())
    for i in range(len(counts)):
        if counts[i] != 0:
            print(chr(ord('a') + i) + "出现" + str(counts[i]) + (" time" if counts[i] == 1 else " times"))

def countLetters(s):
    counts = [0] * 26
    for ch in s:
        if ch.isalpha():
            counts[ord(ch) - ord('a')] += 1
    return counts

main()
</code>

5. Exception Handling

Use try/except blocks to catch errors and keep the program running.

<code>try:
    # code that may raise an exception
except ExceptionType as ex:
    print("Exception:", ex)
</code>

Multiple except clauses can handle different exception types, optionally followed by else and finally blocks.

6. Using the Exception Object

<code>try:
    # risky code
except SomeError as ex:
    print("Exception:", ex)
</code>

7. Raising Exceptions

Raise an exception with raise ExceptionClass("message") . Example:

<code>raise RuntimeError("错误请求")
</code>

8. Custom Exception Classes

Define your own exception by inheriting from BaseException (or a subclass).

<code>class InvalidRadiusException(RuntimeError):
    def __init__(self, radius):
        super().__init__()
        self.radius = radius

class Circle:
    def __init__(self, radius):
        self.setRadius(radius)
    def getRadius(self):
        return self.__radius
    def setRadius(self, radius):
        if radius >= 0:
            self.__radius = radius
        else:
            raise InvalidRadiusException(radius)

def main():
    try:
        c1 = Circle(-5)
    except InvalidRadiusException as ex:
        print("半径是", ex.radius, "不合法")
    except Exception:
        print("一些异常")
    else:
        print("半径是", c1.getRadius())

main()
</code>

9. Binary I/O with Pickle

Use the pickle module to serialize (dump) and deserialize (load) Python objects to/from binary files.

<code>import pickle

# Write an object
with open('data.pkl', 'wb') as f:
    pickle.dump(my_object, f)

# Read objects until EOFError
with open('data.pkl', 'rb') as f:
    while True:
        try:
            obj = pickle.load(f)
            # process obj
        except EOFError:
            break
</code>
PythonException HandlingFile I/OPickleTkinter
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.