首页 > 编程语言 > 详细

Python学习笔记之文件和异常

时间:2018-11-09 13:38:50      阅读:167      评论:0      收藏:0      [点我收藏+]

1、相对路径:如果文件和程序在同一文件夹内,可不用路径;如果文件在程序所在文件夹下一级文件夹中,只需添加下一级文件夹名称即可;

  在Linux和OS系统中:文件路径中使用斜杠(/)         

  在Windows系统中:文件路径使用反斜杠(\)

  通过使用绝对路径,可读取任何地方的文件,但最简单的方法是,要么将文件存储在程序所在的目录,要么存储在程序文件所在目录的下一级文件夹中。

  with open() as 通过使用这个方法打开文件,不需要你手动关闭文件,Python会在合适的机会关闭它。

#open(),read()打开文本文件,并读取内容
with open(‘text_file\word.txt‘) as file_object:
    contents = file_object.read()
    print(str(1)+‘.‘+contents)
#打开文件,逐行读取
with open(‘text_file\word.txt‘) as file_object:
    print(str(2)+‘.‘)
    for line in file_object:
        print(line.rstrip())

2、readlines()在with代码块中将文件内容存储在一个列表中,再在with代码块外打印它

#readlines()函数
with open(‘text_file\word.txt‘) as file_object:
    lines = file_object.readlines()
print(str(3)+‘.‘)
for line in lines:
    print(line.rstrip())

3、统计文件的行数

#每行以下标加行的形式显示
with open(‘text_file\word.txt‘,‘r‘) as f_obj:
    lines = f_obj.readlines()
    count = 0
    for index,line in enumerate(lines):
        count += 1
        print(index,line)
    print(count)

4、转义字符:绝对路径,将长路径存放到变量中,\u\t\n等均为转义字符,需要在路径前加r,不做转义处理

file_path = r‘C:\Users\Administrator\Desktop\Pycharm_Projects\pycharm\text_file\word.txt‘
with open(file_path) as file_object:
    contents = file_object.read()
    print(str(4)+‘.‘+contents)

5、打开文件是,我们可以指定只读模式(‘r‘),写入模式(‘w‘),附加模式(‘a‘),读取和写入模式(‘r+‘),默认以只读模式打开文件。

  如果写入文件不存在,函数open()将自动创建它;

  如果写入模式打开文件,指定的文件已经存在,将在返回文件对象前清空该文件,再重新写入;

  如果以附加模式打开文件,内容会自动添加到文件末尾。

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

#以附加模式写入内容write()
while True:
    user_name = input(‘Enter your name:‘)
    if user_name == ‘q‘:
        break
    else:
        filename = ‘text_file\guests.txt‘
        with open(filename,‘a‘) as file_object:
            file_object.write(user_name + ‘\n‘)
            print(‘Welcome to the white house!‘)
        with open(‘text_file\guests_book.txt‘,‘a‘) as file_object2:
            file_object2.write(‘%s has been to the white house!\n‘%user_name)

6、Python使用被称为“异常”的特殊对象来管理程序运行期间发生的错误,每当发生错误时,它都会创建一个异常对象,如果你编写了处理该异常的代码,

  程序将继续运行,如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

  try-except-else 将可能出现异常的代码放到try下来执行,如果出现异常,执行except下的语句,没有错误的放到else。

#ZeroDivisionError:处理整数不能除以0的异常
print(‘please input two numbers.‘)
print("enter ‘q‘ to quit.")
while True:
    first_number = input("First number:")
    if first_number == ‘q‘:
        break
    second_number = input(‘Second number:‘)
    if second_number == ‘q‘:
        break
    try:
        answer = int(int(first_number)/int(second_number))
    except ZeroDivisionError:
        print(‘You cannot divide by 0!‘)
    else:
        print(answer)

7、处理FileNotFoundError找不到文件异常

def read_file(filename):
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
            print(contents.split(‘,‘))
    except FileNotFoundError:
        msg = "The file %s doesn‘t exist!"%filename
        print(msg)
filename = ‘text_file\cats.txt‘
read_file(filename)
filename = ‘alice.txt‘
read_file(filename)

8、ValueError数值异常

first_number = input("First number:")
second_number = input(‘Second number:‘)
try:
    num = int(first_number) + int(second_number)
except ValueError:
    print(‘wrong data type!‘)
else:
    print(num)

9、pass--定位符,直接跳过,不执行任何程序

def read_file(filename):
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
            print(contents.split(‘,‘))
    except FileNotFoundError:
        pass
filename = ‘alice.txt‘#没有此文件,遇到异常,直接跳过
read_file(filename)
filename = ‘text_file\cats.txt‘
read_file(filename)

10、JSON(JavaScript Object Notation)格式最初是JavaScript开发的,但随后成为一种常见格式,被包括Python在内的众多语言使用。

  模块json能够将简单的Python数据结构存储到文件中,并在程序再次运行时加载该文件中的数据;

  不仅可以在Python程序之间分享数据,还可以与使用其他编程语言的人分享。

  json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象;

  json.load()读取内容

#json.dump()存储,json.load()读取
import json
filename = r‘json_file\favor_number.json‘
try:
    with open(filename, ‘r‘) as f_obj:
        favor_number = json.load(f_obj)
        print(‘I know your favorite number is %d.‘%int(favor_number))
except FileNotFoundError:
    love_number = input(‘enter your favorite number:‘)
    with open(filename,‘w‘) as f_obj:
        json.dump(love_number,f_obj)

11、重构:将代码划分为一系列完成具体工作的函数,这个过程被称为重构。

#重构greet_user(),分成三个函数
import json
def get_new_username():
    ‘‘‘提示用户输入用户名‘‘‘
    filename = r‘json_file\user_name.json‘
    username = input(‘enter your name:‘)
    with open(filename,‘w‘) as f_obj:
        json.dump(username,f_obj)
        return username
def get_stored_username():
    ‘‘‘获取已经存储的用户名‘‘‘
    filename = r‘json_file\user_name.json‘
    try:
        with open(filename,‘r‘) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username
def greet_user():
    ‘‘‘欢迎用户,并指出其名字‘‘‘
    username = get_stored_username()
    print(username)
    if username:#如果函数返回的是用户名,就执行
        judge_flag = input(‘Is the username right?(y/n):‘)#询问用户名是否正确
        if judge_flag == ‘y‘:
            print(‘Welcome back,%s‘ % username)
        else:#如果不正确,提示用户输入用户名,并存储
            username = get_new_username()
            print("We‘ll remember you when you come back,%s."%username)
    else:#如果函数返回的是空,就提示用户输入用户名
        username = get_new_username()
        print("We‘ll remember you when you come back,%s." % username)
greet_user()#运行函数

 

Python学习笔记之文件和异常

原文:https://www.cnblogs.com/charliedaifu/p/9934522.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!