Python学习笔记之文件操作

来源:互联网 发布:李宗仁故居风水数据 编辑:程序博客网 时间:2024/06/07 10:31

image.png

在任何一门编程语言中,文件的操作都是最基本的功能。Python在文件操作方面非常的简单直接,内置了读写文件的函数,在程序中直接调用即可。在读写文件中,会有各种各样的问题,比如文件是否存在,是否有权限,如何捕捉读写异常,这些在Python中都很简单。

读取文件

假设我们在项目目录中已经有了test.txt文件:

file = open('test.txt','r')print(file.read())file.close()

异常处理

try:    file = open('test.txt','r')    print(file.read())except IOError as ierr:    print('Read file error: ' + str(ierr))finally:    if file:        file.close()

使用try-except-finally可以处理文件打开的异常,不过有些麻烦,Python可以使用with open() 来自动关闭文件。

try:    with open('test.txt','r') as file_new:        print(file_new.readline())except IOError as ierr:    print("read file error: " + str(ierr))

写入文件

try:    with open('test1.txt','w') as file_write:        file_write.write('Hello World!')except IOError as ierr:    print("Write file error: " + str(ierr))

如果文件不存在,系统会创建一个新的文件,如果已经存在,会覆盖当前文件。

操作文件目录

import osprint(os.path.abspath('.'))new_dir = os.path.join(os.path.abspath('.'),'testdir')print(new_dir)os.mkdir(new_dir)

使用JSON格式处理

关键字:import json , json.dumps, json.loads

import jsonjson_obj = dict(name='Bob',hobby="basketball")s = json.dumps(json_obj)print(s)json_str='{"order": 12345678,"sold-to": "sd123345"}'d = json.loads(json_str)print(d)

总结

Python文件处理比较简单,JSON格式处理强大,而且更加的普遍实用。

附录 - 源代码

import osprint('文件操作 - 异常处理')try:    file = open('test.txt','r')    print(file.read())except IOError as ierr:    print('Read file error: ' + str(ierr))finally:    if file:        file.close()print('文件操作 - 使用with')try:    with open('test.txt','r') as file_new:        print(file_new.readline())except IOError as ierr:    print("read file error: " + str(ierr))print('文件操作 - 写入文件')try:    with open('test1.txt','w') as file_write:        file_write.write('Hello World!')except IOError as ierr:    print("Write file error: " + str(ierr))try:    with open('test1.txt','r') as file_write:        print(file_write.readline())except IOError as ierr:    print("Write file error: " + str(ierr))print('操作文件目录')print(os.path.abspath('.'))new_dir = os.path.join(os.path.abspath('.'),'testdir')print(new_dir)os.mkdir(new_dir)print("JSON格式处理")import jsonjson_obj = dict(name='Bob',hobby="basketball")s = json.dumps(json_obj)print(s)json_str='{"order": 12345678,"sold-to": "sd123345"}'d = json.loads(json_str)print(d)
原创粉丝点击