【10python基础学习】之文件与异常

本文介绍了Python中的文件读写操作,包括读取整个文件、处理空行、处理不同操作系统路径、逐行读取文件内容、拼接字符串以及检查字符串是否包含在文件中。此外,还讲解了如何将数据写入文件,特别是将数值转换为字符串后再写入。异常处理部分展示了如何捕获和处理错误,如除以零错误和文件未找到错误。最后,给出了一个健壮的用户输入除法运算的程序,确保不会因除零错误而崩溃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读取整个文件

with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())

发现结果有空行出现

windows系统使用的是反斜杠,linux系统使用的是斜杠

print("absolute path to find files")
file_path = 'D:\Icode\forPython\1.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    #print(contents)
    print(contents.rstrip())

每一行进行输出文件内容

file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    for line in file_object:
    print(line)

在代码外面使用每一行

file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    lines = file_object.readline()
for line in lines:
    print(line.rstrip())

使用文件的内容,并判断

file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    lines = file_object.readline()

pi_string = ''
for line in lines:
    pi_string +=line.rstrip()

birth = input("please input your birthda:")
if birth in pi_string:
    print("yes")
else:
    print("no")

print(pi_string)

print(len(pi_string)) 

写入新的文件

Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数
str()将其转换为字符串格式。

第二个实参(‘w’)告诉Python,我们要以写入模式打开这个文件。打开文件时,可指定读取模
式(‘r’)、写入模式(‘w’)、附加模式(‘a’)或让你能够读取和写入文件的模式(‘r+’)。如果
你省略了模式实参,Python将以默认的只读模式打开文件。

file_name = 'programmingData.txt'
with open(file_name,'r+') as file_object:
    file_object.write("  I love wpfei!")
file_name = 'programmingData.txt'
with open(file_name,'r+') as file_object:
file_object.write("  I love wpfei!\n")
file_object.write("  I love  hhhh!")

附加到的文件后面
只需要很简单的操作,将控制的参数改为‘a’即可

异常

Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知
所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运行;
如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

print(2/0)

Traceback (most recent call last):
  File "d:\Icode\forPython\02file_open.py", line 1, in <module>
    print(2/0)
ZeroDivisionError: division by zero


try:
    print(2/0)
except ZeroDivisionError:
    print("you can not division by zero!!!") 

[Running] python -u "d:\Icode\forPython\02file_open.py"
you can not division by zero!!!

[Done] exited with code=0 in 0.154 seconds


print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer) 
        


可以写出十分健壮的程序
文件查找不到的异常

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj) 
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值