python读取/写入文件

Python编程:从入门到实践》读书笔记

1.读取文件并且对文件内容进行打印有三种方式:

with open('test.txt') as fo:
    for lins in fo:
        print(lins.rstrip())
    

with open('test.txt') as fo:
    lines=fo.read()
    print(lines.rstrip())


with open('test.txt') as fo2:
    lt=fo2.readlines()
for l in lt:
    print(l.rstrip())

 1)读取之后使用for循环遍历文件对象 进行打印

2)直接读取文件对象打印。

 3)将文件内容存到列表里,在with代码块外打印。(需要遍历列表,rstrip方法是字符串的,不是列表的。)

 2.将内容写入到文件:

直接使用write函数,在open时制定参数'w',写入时会将原来文件中所存储的信息删除,重新写入。

fn='test.txt'

with open(fn,'w') as fo:
    fo.write("hello world")

可以将打开方式变为‘a’,就是追加文件内容。r+是可读可写。

3.使用while和异常结合实现加法:

a=input('first:')
b=input('second:')

while True:
    try:
        aa=int(a)
        bb=int(b)
        c=aa+bb
    except ValueError:
        print('Error!!!Try again')
        a=input('first:')//需要重新读入数据
        b=input('second:')
    else:
        print(c)
        break

写的时候遇见了一个问题就是死循环打印Error. 在except中加入continue还是死循环。

原因是需要重新读入数据。

原文地址:https://www.cnblogs.com/BlueBlueSea/p/9748674.html