本篇文章给大家带来的内容是关于Python中对文件的相关处理操作的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

open() 方法

Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

完整的语法格式为:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

file: 必需,文件路径(相对或者绝对路径)。

mode: 可选,文件打开模式

buffering: 设置缓冲

encoding: 一般使用utf8

errors: 报错级别

newline: 区分换行符

closefd: 传入的file参数类型

opener:>>> with open('F://lixu.txt','r') as f:

... print(f.read())

...

大家好,我叫李*!

>>> try:

... f = open('F://lixu.txt',mode='r')

... print(f.read())

... finally:

... if f:

... f.close()

...

大家好,我叫李*!def readData(self,datafile = None):

"""

read the data from the data file which is a data set

"""

self.datafile = datafile or self.datafile

self.data = []

for line in open(self.datafile):

userid,itemid,record,_ = line.split()

self.data.append((userid,itemid,int(record)))

read()

read() 方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。>>> with open('F://lixu.txt','r') as f:

... print(f.read())

...

大家好,我叫李*!

readline()

readline() 方法用于从文件读取整行,包括 “\n” 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 “\n” 字符。文件内容:

1:www.runoob.com

2:www.runoob.com

3:www.runoob.com

4:www.runoob.com

5:www.runoob.com

# 打开文件

fo = open("runoob.txt", "rw+")

print "文件名为: ", fo.name

line = fo.readline()

print "读取第一行 %s" % (line)

line = fo.readline(5)

print "读取的字符串为: %s" % (line)

# 关闭文件

fo.close()

文件名为: runoob.txt

读取第一行 1:www.runoob.com

读取的字符串为: 2:www

readlines()

readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。

如果碰到结束符 EOF 则返回空字符串。def file2matrix(filename):

"""

从文件中读入训练数据,并存储为矩阵

"""

fr = open(filename)

arrayOlines = fr.readlines()

numberOfLines = len(arrayOlines) #获取 n=样本的行数

returnMat = zeros((numberOfLines,3)) #创建一个2维矩阵用于存放训练样本数据,一共有n行,每一行存放3个数据

classLabelVector = [] #创建一个1维数组用于存放训练样本标签。

index = 0

for line in arrayOlines:

# 把回车符号给去掉

line = line.strip()

# 把每一行数据用\t分割

listFromLine = line.split('\t')

# 把分割好的数据放至数据集,其中index是该样本数据的下标,就是放到第几行

returnMat[index,:] = listFromLine[0:3]

# 把该样本对应的标签放至标签集,顺序与样本集对应。

classLabelVector.append(int(listFromLine[-1]))

index += 1

return returnMat,classLabelVector

区别>>> f = open('F://lixu.txt',mode='r')

>>> line2 = f.readline()

>>> print(line2)

大家好,我叫李*!

>>> f = open('F://lixu.txt',mode='r')

>>> line = f.read()

>>> print(line)

大家好,我叫李*!

啦啦啦

>>> f = open('F://lixu.txt',mode='r')

>>> line = f.readlines()

>>> print(line)

['大家好,我叫李*!\n', '\n', '啦啦啦\n', '\n', '\n']