美文网首页
Python文件处理

Python文件处理

作者: 刘开心_8a6c | 来源:发表于2017-03-13 08:26 被阅读0次

文件读取


整个读取


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)

相关文章

  • Python 文件处理

    Python 读文件处理 1. readline() with 处理开闭文件&文件异常处理 readline()内...

  • 从Excel到Python (视频)

    Python Pandas处理Excel文件

  • Python 文件处理

    文件的理解 文件是数据的抽象和集合 文本文件 VS. 二进制文件 f.txt 文件保存: "人生苦短, 我用Pyt...

  • Python 文件处理

    文件处理 常用打开文件方式 1.读取文件内容, 模式为 'r' 表示读, 这也是打开的默认方式。 2.如果要创建或...

  • python 文件处理

  • python——文件处理

    1.文件处理 如果报错 说明编码不对。 按正常逻辑来讲,文件是以什么方式存的,就应该用什么方式去读取,比如以gb2...

  • Python 文件处理

    python 文件打开方式 文件打开方式: open(name[,mode[,buf]])name: 文件路径mo...

  • Python 文件处理

    创建文件 f = file('myfile.txt','w') f.write('hello,baby!')f....

  • python 文件处理

    文件处理有三个步骤:1、定义文件路径: 2、打开并保存文件内容。 r:以只读方式打开文件。文件的指针将会放在文件的...

  • Python文件处理

    文件读取 整个读取 两个注意点: 使用关键字with可以自动关闭文件流,如果使用file_object = ope...

网友评论

      本文标题:Python文件处理

      本文链接:https://www.haomeiwen.com/subject/tucfnttx.html