胖蔡说技术
随便扯扯

Python 中的文件操作

python中对于数据输入输出的处理和常规性语言类似。主要包括:系统输入输出、文件存储、数据库存储等,其中数据存储读取操作中主要就是对于文件和数据库的处理方面。python中对于文件的处理提供了一个比较常用且比较方便的内建类file,通过file可以比较方便的对文件操作。python中对于文件的操作较多的方法可以很方便的实现文件的读取、写入、删除、查找等操作,如下示例:

#!/usr/bin/env python
#-*-encoding:utf-8-*-

import  sys,fileinput,codecs

testFile = file('testFile.txt')
# 文件读操作
# print testFile.read()
# 文件单行读操作.
print testFile.readline()
# 文件单行制定字符读操作.
print testFile.readline(3)
# 文件读所有行,并返回一个list.
# print testFile.readlines()
print "file name:",testFile.name
# 文件迭代
print testFile.next()
print next(testFile)

# 返回一个整型的文件描述符,可供底层操作系统调用.
print testFile.fileno()

try:
    testFile.write("test")
except Exception as e:
    print e

# 关闭文件
testFile.close()

# with  open(name="testFile.txt",mode='wb+',buffering=1024) as testFile:
#     testFile.write("print \"append mode------------------------------ 1\"")
#     print testFile.read()

with  open(name="testFile.txt",mode='a+') as testFile:
    testFile.write("print \"append mode------------------------------2 \"")
    testFile.flush()
    testFile.seek(0)
    for line in testFile:
        print "line:",line

# fileinput
testFile =  fileinput.input('testFile.txt') 
for line in testFile:
    print line
    testFile.close()
    break

# print testFile.filename()

# codecs
with codecs.open('testFile.txt','rb',encoding='utf-8') as testFile:
    print '\n\n\n'
    print testFile.read(10)

# print help(open)
# print file.__doc__
蔡海飞

123
file name: testFile.txt
456

pwd

87
File not open for writing
line: 蔡海飞

line: 123456

line: pwd

line: 男

line: 1992print "append mode------------------------------2 "print "append mode------------------------------2 "
蔡海飞





蔡海飞
123456
pwd

python文件操作,打开文件可以通过指定文件操作的模式类型从而赋予文件操作的不同权限,python中对于文件的模式甚至如下几个类型:

  • r
    模式’r’为读模式,一般不制定文件打开的模式时默认为读模式
  • w
    模式’w’为写模式
  • b
    模式’b‘为以二进制格式打开文件,该模式一般会和其他模式混合使用如:’rb’、’wb‘,’ab’等
  • a
    模式’a’为追加模式,一般特指写模式的追加,一般的写模式’w’执行写操作时若文件存在则直接覆盖(指针指向开始位置),若不存在则创建,而’a’模式下的文件写操作则是若文件存在,则指针指向文件结尾追加写入,若文件不存在则创建。

同时允许通过在模式后添加一个’+’来来实现文件的读写。如’r+’、’rb+’、’w+’、’wb+‘、’a+‘、’ab+‘。文件打开还有一个参数是设置文件的buffering的,当buffering为0表示不设置缓存,buffering为1则表示缓存为一行,当其他大于1的数字则表示缓存的大小。如上,文件的打开可以使用系统自带的内置类file或者内置函数open函数,也可以通过fileinput模块或者codecs(可以对文件打开设置编码)模块进行打开。

赞(0) 打赏
转载请附上原文出处链接:胖蔡说技术 » Python 中的文件操作
分享到: 更多 (0)

请小编喝杯咖啡~

支付宝扫一扫打赏

微信扫一扫打赏