一天快速入门Python语法基础之文件和异常

#一、从文件中读取数据
#1读取整个文件
with open('pai.txt') as file_object:
    contents=file_object.read()
    print(contents)

#2文件路径
file_path='C:\\Users\\dell\\Desktop\\pai.txt'
with open(file_path) as file_object:
    contents=file_object.read()
    print(contents)
    #window读取文件可以用\,但是在字符串中\是被当作转义字符来使用,所以用\\

#3逐行读取
filename='pai.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line)

#4创建一个包含文件各行内容的列表
filename='pai.txt'
with open(filename) as file_object:
    lines=file_object.readlines()
    for line in lines:
        print(line.rstrip())

#5使用文件的内容
#将文件读取到内存中后,就可以以任何方式使用这些数据了
filename="pai.txt"
with open(filename) as file_object:
    lines=file_object.readlines()
pi_string=' '
for line in lines:
    pi_string+=line.rstrip()
print(pi_string)
print(len(pi_string))

 

#二、写入文件
#1 写入空文件
#要将文本写入文件,首先要打开再写入
filename='pai.txt'
with open(filename,'w') as file_object:
    file_object.write("l like python")
#如果要写入的文件不存在,函数open将自动创建,
#以写入('w')模式打开文件,如果指定文件已存在,python将清空之前内容后在写入
#python只能将字符串写入文本文件,要将数值数据存储到文本文件中,需先使用str()将其转换为字符串格式

#2 写入多行
#函数write()不会在你写入的文本中添加换行符,要让每个字符串都独占一行
filename="pai.txt"

with open(filename,'w') as file_object:
    file_object.write("i lik java\n")
    file_object.write("i like c++\n")
#与显示在终端的输出一样,还可以使用空格,制表符,等来设置输出格式

#3 附加到文件
#如果你要给文件添加内容,而不是覆盖删除原有内容,可以附加模式打开文件
filename='pai.txt'
with open(filename,'a') as file_object:
    file_object.write("i also like ruby\n")
    file_object.write("l also like js\n")

 

#三、处理FileNotFoundError异常
#使用文件时,一种常见的问题是找不到文件,对于这种情况以try-except代码块来处理
filename="no.txt"
try:
    with open(filename) as f_obj:
       contents=f_obj.read()
except FileNotFoundError:
    msg="文件不存在"
    print(msg)

#分析文本
#下面提取pai.txt文本 并尝试计算它包含多少个单词
#我们将使用split()方法,它根据一个字符串创建一个单词列表
filename="pai.txt"  #可将filenames定义成列表,用来处理多个文件
try:
    with open(filename) as f_obj:
       contents=f_obj.read()
except FileNotFoundError:
    msg="文件不存在"
    print(msg)
else:
    words=contents.split()
    num_words=len(words)
    print(str(num_words))

参考:《Python编程:从入门到实践》,本书作者Eric Matthes,译者袁国忠,由人民邮电出版社于2016年7月出版

posted @ 2018-03-18 02:44  锅锅7533  阅读(131)  评论(0编辑  收藏  举报