Python文件处理

文件读取


整个读取


with open('pi_digits.txt') as file_object:

contents = file_object.read()

print(contents)

两个注意点:

  • 使用关键字with可以自动关闭文件流,如果使用file_object = open('pi_digits.txt')这种方式则需要手动关闭文件流,手动关闭带来的问题就是假设程序在过程中存在bug,导致close()语句未执行,文件将不会关闭,就会带来数据丢失或损失的问题,所以这是推荐写法。

  • open的参数可以写相对路径,也可以写绝对路径,在Mac种使用“/”分隔;在windows种使用“\”分隔,另外,由于反斜杠在Python中被视为转义,为在windows种万无一失可以用原始字符串的方式指定路径,即在开头的单引号前加上r。(没用过此方式,不如出了问题再用)

  • read()到达文件末尾时会返回一个空串,显示出来就是空行,想删除该空行,可以使用rstrip()函数,print(file_object.read().rstrip())

逐行读取


filename = 'pi_digits.txt'

with open(filename) as file_object:

for line in file_object:

print(line)
  • 将文件名存在filename中,就可以方便替换文件名,而不用动下面的代码

  • 在打印结果中会发现每一行下面都有一个空白行,因为print语句会加上一个换行符,要消除这些空白行,可在print语句中使用rstrip():print(line.rstrip())

将文件内容读取到内存中

存储到列表中

filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

for line in lines:

print(line.rstrip)
存储到字符串中

filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

pi_string= ''

for line in lines:

pi_stirng += line.strip()

print(pi_string)

print(len(pi_string))

注意点:

  • 删除空格使用strip()函数,删除空行使用rstrip()函数

  • 对于可以处理的数据量,Python没有任何限制,只要系统的内存足够多,想处理多少数据都可以

判断文件中是否包含某内容


filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

pi_string= ''

for line in lines:

pi_stirng += line.strip()

birthday = input('Enter your birthday, in the form mmddyy:')

if birthday in pi_string:

print('Your birthday appeears in the first million digits of pi!')

else:

print('Your birthday does not appear in the first million digits of pi.')

读json格式的数据


filename = 'numbers.json'

with open(filename) as f_obj:

numbers = json.load(f_obj)

print(numbers)

文件写入

写入空文件


improt json

filename = 'programing.txt'

with open(filename, 'w') as file_object:

file_object.write("I love programming")
  • w,写入模式,如果文件已存在,将覆盖

  • a,附加模式,如果文件已存在,则附加,否则新建

  • r+,读写模式

  • Python只能将字符串写入文件,所以如果是数值数据,需用str()转换

写入json格式的数据


improt json

numbers = [2,3,5,7,11,13]

filename = 'numbers.json'

with open(filename, 'w') as f_obj:

json.dump(numbers, f_obj)

文件异常处理

很多初学者都没有在程序中写异常的意识,这会给程序带来很多危险,比如程序突然崩溃,攻击者可能会根据traceback对代码发起攻击,一般在涉及到数据交互,输入输出等地方,都要写异常处理语句。写法如例:


print("Give me two numbers, and I'll devide them.")

print("Enter 'q' to quit.")

while True:

first_number = input(\nFirst number:)

if first_number == 'q':

break

second_number = input(\nSecond number:)

try:

answer = int(first_number) / int(second_number)

except ZeroDivisionError:

print("You can't dividee by 0!")

else:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值