文件和异常

先创建一个文件pi_digits.txt

3.1415926535
  8979323846
  2643383279

再创建一个程序打开并读取这个文件

file_reader.py

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

如果文件在一个文件夹中那么用

with open('cc/filec.txt') as file_object:
    contents = file_object.read()
print(contents)

        还可以将文件在计算机中的准确位置告诉Python,这样就不用关心当前运行的程序存储在什么地方了。这称为绝对文件路径。

with open('E:/Pythonkl/filed.txt') as file_object:
    contents = file_object.read()
print(contents)

或者

with open('E:\\Pythonkl\\filed.txt') as file_object:
    contents = file_object.read()
print(contents)

逐行读取

        读取文件时,常常需要检查其中的每一行:可能要在文件中查找特定的信息,或者要以某种方式修改文件中的文本。

filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)

创建一个包含文件各行内容的列表

        下面的示例在with代码块中将文件pi_digits.txt的各行存储在一个列表中,再在with代码块外打印:

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

        readlines()从文件中读取每一行,并将其存储在一个列表中。接下来,该列表被赋给变量lines。在with代码块外,依然可使用这个变量。使用一个简单的for循环来打印lines中的各行。因为列表lines的每个元素都对应于文件中的一行,所以输出与文件内容完全一致。
 


使用文件的内容

        将文件读取到内存中后,就能以任何方式使用这些数据了。下面以简单的方式使用圆周率的值。首先,创建一个字符串,它包含文件中存储的所有数字,且没有任何空格。

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

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

print(pi_string)
print(len(pi_string))

        这样就获得了一个字符串,其中包含准确到30位小数的圆周率。这个字符串长32字符,因为它还包含整数部分的3和小数点。

        注意:读取文本文件时,Python将其中的所有文本都解读为字符串。如果读取的是数,并要将其作为数值使用,就必须使用函数int()将其转换为整数或使用函数float()将其转换为浮点数。


圆周率值中包含你的生日吗?

        下面来扩展刚才编写的程序,以确定某个人的生日是否包含在圆周率值的前1000000位中。为此,可将生日表示为一个由数字组成的字符串,再检查这个字符串是否包含在pi_string中:

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

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

birthday = input("Enter your birthday,in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi!")

写入文件

写入空文件

        要将文本写入文件,你在调用open()时需要提供另一个实参,告诉Python你要写入打开的文件。

filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love programming.")

        在本例中,调用open()时提供了两个实参,第一个实参也还要打开的文件的名称。第二个实参(‘w’)告诉Python,要以写入模式打开这个文件。打开文件时,可指定读取模式(‘r’),写入模式(‘r’),附加模式(‘a’)或读写模式(‘r+’).如果省略了模式实参,Python将以默认的只读模式打开文件。

        如果要写入的文件不存在,函数open()将自动创建它。然而,以写入模式('w')打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件的内容。

注意:Python只能将字符串写入文本文件,这个文件没有什么不同。你可以打开它、在其中输入新文本、复制其内容、将内容粘贴到其中,等等。


写入多行

        函数write()不会再写入的文本末尾添加换行符,因此如果写入多行时没有指定换行符,文件看起来可能不是你希望的那样。

filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love programming.")
    file_object.write("I love creating new games.")

结果:

I love programming.I love creating new games.

要让每个字符串都单独占一行,需要在方法调用write()中包含换行符:

filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

附加到文件

       如果要给文件添加内容,而不是覆盖原有的内容可以以附加模式打开文件。以附加模式打开文件时,Python不会在返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾。如果指定的文件不存在,Python将为你创建一个空文件。

        下面在既有文件programming.txt中再添加一些你酷爱编程的原因:

filename = 'programming.txt'
with open(filename,'a') as file_object:
    file_object.write("I also love finding meaning in large datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

结果:

I love programming.
I love creating new games.
I also love finding meaning in large datasets.
I love creating apps that can run in a browser.

练习:

1、编写一个程序,提示用户输入名字。用户做出响应后,将其名字写入文件guest.txt中。

message = input("Enter your name:")
filename = 'guest.txt'
with open(filename,'w') as file_object:
    file_object.write(message)

2、编写一个while循环,提示用户输入名字。用户输入名字后,在屏幕上打印一句问候语,并将一条到访记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

filename = 'guest.txt'
flag = True
while flag:
    message = input("Enter you name:")
    if message == 'q':
        break
    else:
        print(f"Hello, {message}")
        with open(filename,'a') as file_object:
            file_object.write(message)

异常

处理ZeroDivisionError异常

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

使用异常避免崩溃

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("\nSecond number:")
    if second_number == 'q':
        break
    try:
        answer = int(first_number)/int(second_number)
    except ZeroDivisionError:
        print("You can't divide by zero!")
    else:
        print(answer)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值