Home >Backend Development >Python Tutorial >Introduction to file-related processing operations in Python (with code)

Introduction to file-related processing operations in Python (with code)

不言
不言forward
2018-10-27 16:07:562339browse

This article brings you an introduction to file processing operations in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

open() method

Python open() method is used to open a file and return the file object. This function needs to be used during file processing. If the The file cannot be opened and an OSError will be thrown.

Note: When using the open() method, you must ensure that the file object is closed, that is, the close() method is called.

The common form of the open() function is to receive two parameters: file name (file) and mode (mode).
The complete syntax format is:

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() method is used to read the specified number of bytes from the file. If not given If set or negative, all are read.

>>> with open('F://lixu.txt','r') as f:
...     print(f.read())
...
大家好,我叫李*!

readline()

readline() method is used to read the entire line from the file, including the "\n" character. If a non-negative argument is specified, returns the specified size in bytes, including the "\n" character.

文件内容:
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() method is used to read all lines (until the end character EOF) and return a list, which can be used by Python’s for… in … structure is processed.
If the end character EOF is encountered, an empty string is returned.

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

DIFFERENCE

>>> 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']

The above is the detailed content of Introduction to file-related processing operations in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete