a19_Python文件I/O---学习笔记

本章将覆盖所有在Python中使用的基本I/O功能。有关更多函数,请参考标准Python文档。

打印到屏幕上:

产生输出最简单的方法是使用print语句,可以通过用逗号分隔的零个或多个表达式。该函数将传递到一个字符串表达式,并将结果写到标准输出,如下所示:

#!/usr/bin/python
print("Python is really a great language,","isn't it?");

这将产生结果输出在标准屏幕上,结果如下:

Python is really a great language, isn't it?

读取键盘输入:

Python提供了两个内置的函数来读取一行,从标准输入,默认情况下是来自键盘的文本。这些函数包括:

  • raw_input

  • input

raw_input 函数:

raw_input([prompt])函数从标准输入读取一行并返回一个字符串(去掉结尾的换行)。

#!/usr/bin/python

str = raw_input("Enter your input: ");

pritn("Received input is : ",str )

 执行上面程序,返回下面结果:

Enter your input: lily
Received input is :  lily

input函数:

input([prompt]) 函数相当于raw_input,只是它假设输入的是一个有效的Python表达式,并返回计算结果。

#!/usr/bin/python
str = input("Enter your input: ");
print("Received input is : ",str)

对所输入这将产生结果如下:

Enter your input:  [x*5 for x in range(2,10,2)]
Received input is :   [x*5 for x in range(2,10,2)]

打开和关闭文件:

到现在为止,已经了解读取和写入标准输入和输出。现在,我们看看如何用实际数据文件。

Python提供了基本的函数和必要在默认情况下对文件进行操作的方法。可以使用一个文件对象file来做大部分文件操作。

open 函数:

想要读取或写入文件,必须使用Python内置的open()函数来打开它。该函数创建一个文件对象,这将用来调用与之关联的其他支持方式。

语法:

file object = open(file_name [,assess_mode][,buffering])

下面是参数的详细信息:

  • file_name: file_name参数是一个字符串值,包含您要访问的文件的名称。

  • access_mode: access_mode决定了文件必须被打开,即,读,写,追加等的可能值是下表中给定的一个完整的列表的模式。这是可选参数,默认文件存取方式为read (r)。

  • buffering: 如果缓冲值被设置为0时,没有缓冲将发生。如果该缓冲值是1,行缓冲会在访问一个文件来执行。如果指定的缓冲值为大于1的整数,则缓冲作用将与所指示的缓冲区的大小进行。如果为负,则缓冲区的大小是系统默认(默认行为)。

这里是打开一个文件的​​不同模式的列表:

模式 描述
r 打开一个文件为只读。文件指针置于该文件的开头。这是默认模式。
rb 打开一个文件只能以二进制格式读取。文件指针置于该文件的开头。这是默认模式。
r+ 打开用于读取和写入文件。文件指针将会在文件的开头。
rb+ 打开用于读取和写入二进制格式的文件。文件指针将会在文件的开头。
w 打开一个文件只写。覆盖该文件,如果该文件存在。如果该文件不存在,则创建用于写入一个新的文件。
wb 打开一个文件只能以二进制格式写入。覆盖该文件,如果该文件存在。如果该文件不存在,则创建用于写入一个新的文件。
w+ 打开用于写入和读取的文件。覆盖现有的文件,如果文件存在。如果该文件不存在,则创建读取和写入新的文件。
wb+ 打开用于写入和读取的二进制格式的文件。覆盖现有的文件,如果文件存在。如果该文件不存在,则创建读取和写入新的文件。
a 将打开追加文件。文件指针是在文件的结尾。也就是说,该文件是在附加模式。如果该文件不存在,它创造了写入一个新的文件。
ab 将打开追加的二进制格式的文件。文件指针在该文件的结束。也就是说,该文件为追加模式。如果该文件不存在,它创建并写入一个新的文件。
a+ 打开为追加和读取文件。文件指针在该文件的结束。该文件将为追加模式。如果该文件不存在,它创建并读取和写入的新文件。
ab+ 打开两个追加和读取的二进制格式的文件。文件指针在该文件的结束。该文件将在追加模式。如果该文件不存在,它创建并读取和写入的新文件。

 

file 对象属性:

一旦文件被打开,文件对象可以得到有关该文件的各种信息。

下面是文件对象相关的所有属性的列表:

属性 描述
file.closed 如果文件被关闭则返回true,否则返回false。
file.mode 返回该文件被打开的访问模式。
file.name 返回文件的名称。
file.softspace 如果空间明确要求具有打印返回false,否则返回true。
#!/usr/bin/python
#Open a file
fo = open("foo.txt","wb")
print("Name of the file: ",fo.name)
print ("Closed or not: ",fo.closed)
print("Opening mode : ",fo.mode)
print("Softspace flag: ",fo.softspace)

对所输入这将产生结果如下:

Traceback (most recent call last):
Name of the file:  foo.txt
  File "F:/pythonDEV/简明python笔记/Python文件IO/open_foo_file.py", line 7, in 
Closed or not:  False
    print("Softspace flag: ",fo.softspace)
Opening mode :  wb
AttributeError: '_io.BufferedWriter' object has no attribute 'softspace'

close() 方法:

一个文件对象的close()方法刷新未写入的信息,并关闭该文件的对象,在这之后没有数据内容可以执行写入。

Python自动关闭,当文件的引用对象被重新分配给另外一个文件。它是使用close()方法来关闭文件是一个很好的做法。

语法:

fileObject.close();

例子:

#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print("Name of the file: ",fo.name)
#Close opend file
fo.close()

对所输入这将产生结果如下:

Name of the file:  foo.txt

读取和写入文件:

file对象提供了一组访问方法。我们来看看如何使用read()和write()方法来读取和写入文件。

write() 方法:

write()方法写入字符串到任何一个打开的文件。要注意的是Python字符串可以具有二进制数据,而不仅仅是文字。

write()方法不要将换行字符('n')添加到字符串的结尾:

语法:

fileObject.write

这里,传递的参数是要写入到打开的文件的内容。

python的bytes和str两种类型转换的函数encode()、decode()

  • str通过encode()方法可以编码为指定的bytes;
  • 反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法;

例子

#!/usr/bin/python
#Open a file
fo = open("foo.txt","wb")
str = 'Python is a great language . nYeah its great!!n'
str = str.encode()
#fo.write(bytes(str,'UTF-8')) 第二种写法
fo.write(str)
#Close opend file
fo.close()
print('关闭文件成功!')

对所输入这将产生结果如下:

关闭文件成功!

read() 方法:

read()方法读取一个打开的文件的字符串。要注意的是Python字符串可以具有二进制数据,而不仅仅是文本。

语法

fileObject.read([count]);

这里,传递的参数是从打开的文件中读出的字节数。此方法从该文件的开头读取,如果计数丢失,那么它会尝试尽可能多地读取,直到文件的末尾。

例子:

这里以一个文件foo.txt作为例子,这是在上面创建的。

#!/usr/bin/python
#Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print("Read String is : " ,str)

#Close opend file
fo.close()

 执行上面程序,返回下面结果:

Read String is :  Python is 

文件位置:

tell()方法告诉该文件中的当前位置;换句话说,下一个读取或写入将发生在从该文件的开头的字节数。

seek(offset[, from]) 方法会更改当前的文件位置。偏移参数指示要移动的字节数。从该参数指定字节将被移至参考点。

如果from被设置为0,这意味着使用该文件的开始处作为基准位置,设置为1则是使用当前位置作为基准位置,如果它被设置为2,则该文件的末尾将被作为基准位置。

例子

让我们以一个文件foo.txt,这是上面创建。

#!/usr/bin/python
#Open a file
fo = open("foo.txt","r+")
str = fo.read(10);
print ("Read String is : ", str)

# Check current position 检查当前位置
position = fo.tell( ); #下一个读取或写入将发生在从该文件的开头的字节数
print ("Current file position : ", position)

#Reposition pointer at the beginning once again 再次将指针重新放置在开头
position = fo.seek(0,0); #方法会更改当前的文件位置。偏移参数指示要移动的字节数。从该参数指定字节将被移至参考点。
str = fo.read(10);
print("Again read String is : ",str)

#Close opend file
fo.close()

 执行上面程序,返回下面结果:

Read String is :  Python is 
Current file position :  10
Again read String is :  Python is 

重命名和删除文件:

Python的os模块提供了一些方法,可以帮助执行文件处理操作,如重命名和删除文件。

要使用这个模块,需要先导入它,然后调用相关的功能。

rename() 方法:

rename()方法有两个参数,当前文件名和新文件名。

语法:

os.rename(current_file_name,new_file_name)

例子

以下是例子来重命名文件test1.txt:

#!/usr/bin/python
import os
# Rename a file from text1.txt to text2.txt
os.rename("text1.txt","text2.txt")

remove() 方法:

可以使用remove()方法通过提供参数作为文件名称作为要删除的文件。

语法:

os.remove(file_name)

例子

以下为示例删除现有文件test2.txt:

#!/usr/bin/python
import os
#Delete file text2.txt
os.remove("text2.txt")

Python中的目录:

所有的文件都包含不同的目录中,而在Python中处理这些没有问题。os模块有几种方法,可以帮助创建,删除和更改目录。

mkdir() 方法:

可以使用os模块的mkdir()方法在当前目录下创建目录。需要提供参数,这个方法包含的目录要创建的名称。

语法:

os.mkdir("newdir")

例子:

以下为示例在当前目录下创建test目录如下所示:

#!/usr/bin/python
import os
#Create a directory "test"
os.mkdir("test")

python创建一个txt文件

#!/usr/bin/python

#创建一个txt 文件,文件名为text1,并向文件写入msg

def text_create(name,msg):
    desktop_path = "F:\\pythonDEV\\简明python笔记\\Python文件IO\\" #创建的txt文件的存放路径
    full_path= desktop_path + name + '.txt' #也可以创建一个。doc的word文档
    file = open(full_path,'w')
    file.write(msg) #msg也就是下面的 Hello world!
    #file.close()
text_create('text1','Hello world!')

chdir() 方法:

可以使用chdir()方法来改变当前目录。chdir()方法接受一个参数,那就是要成为当前目录的目录的名称。

语法:

os.chdir("newdir")

例子:

下面是一个进入“F:\pythonDEV\简明python笔记\Python文件IO\test1”目录的例子:

#!/usr/bin/python
import os
#Changing a directory to "F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1"
os.chdir("F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1")

getcwd() 方法:

getcwd()方法显示当前的工作目录。

例子:

os.getcwd()

例子:

以下是例子给定为当前目录:

#!/usr/bin/python
import os
#Changing a directory to "F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1"
os.chdir("F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1")
#This would give location of the current directory
print (os.getcwd())

 执行上面程序,返回下面结果:

F:\pythonDEV\简明python笔记\Python文件IO\test1

rmdir() 方法:

rmdir()命令方法删除目录,它是通过方法的参数。

在删除一个目录,它的所有内容应该被删除。

语法:

os.rmdir('dirname')

例子

下面是一个例子删除“F:\pythonDEV\简明python笔记\Python文件IO\test1\test11”目录。它是必需的,得到的目录完全的名称,否则将搜索在当前目录中的目录。

# -*- coding:utf-8 -*-
#!/usr/bin/python
# Author:Kenken liu
import os
import subprocess
#创建一个文件
os.mkdir("F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1\\test11")
#创建一个txt1.txt,内容为Hello LinKen!
def txt_create(name,meg):
    desktop_path ="F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1\\"
    full_path =desktop_path + name + '.txt'
    file = open(full_path,'w')
    file.write(meg)
txt_create('txt1','Hello LinKen!')
#切换到目录下,并且显示当前目录
os.chdir("F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1")
print (os.getcwd())
#读取txt1.txt,文本内容
fo = open("txt1.txt","r+")
str = fo.read();
print("Read String is: ", str)
#更改文本内容:Hello KenKen! Let\'s be friends
txt_create('txt1','Hello KenKen! Let\'s be friends')
#重新读取文本内容
fo = open("txt1.txt","r+")
str = fo.read();
print("Read String is: ", str)
#关闭当前文件
fo.close()
#改名
os.rename("txt1.txt","txt2.txt")
#复制txt2,txt到txt3.txt
src = "txt2.txt"
dst = "txt3.txt"
cmd = 'copy "%s" "%s" '% (src,dst)
status =subprocess.call(cmd,shell = True)
if status !=0:  #状态
    if status < 0:
        print ("Killed by signal",status) #打印杀死的信号状态
    else:
        print ("Command failed with return code - ",status) #打印命令失败,返回码状态
else:
    print ('Execution of %s passed!\n' % cmd)  #打印,执行通过

#删除txt3.txt文本文件
os.remove("txt3.txt")
#删除目录
os.rmdir('F:\\pythonDEV\\简明python笔记\\Python文件IO\\test1\\test11')

文件和目录相关的方法:

有三个重要来源,它提供了一些工具和方法来处理和操作在Windows和Unix操作系统的文件和目录。它们如下:

  • File对象方法: 文件file 对象提供函数来对文件进行操作。

  • OS对象方法: 这提供了一些方法来处理的文件以及目录。

File对象方法:

使用open函数创建一个文件对象,这里是它可以调用该对象上函数的列表如下:

SN 方法与描述
1 file.close()
关闭文件。关闭的文件无法读取或写入任何东西
2 file.flush()
刷新内部缓冲区,像标准输入输出fflush。这可能是一些类似文件的对象,无操作
3 file.fileno()
返回所使用的底层实现请求从操作系统I/O操作的整数文件描述符
4 file.isatty()
返回true如果文件被连接到一个tty(一般)的设备,否则返回False
5 file.next()
返回每次被调用时文件的下一行。
6 file.read([size])
读取最多的字节大小的文件(如果少读命中EOF获得大小字节之前)
7 file.readline([size])
从文件中读取一个完整的行。尾部换行符保持在字符串中
8 file.readlines([sizehint])
读取直到EOF使用readline()返回一个包含行的列表。如果可选sizehint参数不是读取达到EOF,全行共计约sizehint字节(可能四舍五入到内部缓冲区的大小后)被读取
9 file.seek(offset[, whence])
设置文件的当前位置
10 file.tell()
返回该文件的当前位置
11 file.truncate([size])
截断文件的大小。如果可选的尺寸参数存在,该文件被截断(最多)大小
12 file.write(str)
将一个字符串写入该文件。没有返回值
13 file.writelines(sequence)
写入字符串的文件的序列。该序列可以是任何可迭代的对象产生字符串,通常的字符串列表

close()方法的语法结构:

close()方法方法关闭打开的文件。关闭的文件无法读取或写入更多东西。文件已被关闭之后任何操作会引发ValueError。但是调用close()多次是可以的。

Python自动关闭,当一个文件的引用对象被重新分配给另外一个文件。它使用close()方法来关闭一个文件一个很好的做法。

语法

以下是close()方法的语法:

fileObject.clost();

参数

  • NA

返回值

此方法不返回任何值

例子

下面的例子显示了close()方法的使用

# -*- coding:utf-8 -*-
#!/usr/bin/python
#Author:Kenken Liu
#关闭文件。关闭的文件无法读取或写入任何东西

#open a file
fo = open("foo.txt","wb")
print ("Name of the file: ",fo.name)
print ("Closed or not : ",fo.closed)
print ("Opening mode : ",fo.mode)
#print ("Softspace flag: ",fo.softspace)

fo.close()
print ("Name of the file: ",fo.name)
print ("Closed or not : ",fo.closed)
print ("Opening mode : ",fo.mode)
#print ("Softspace flag: ",fo.softspace)

 执行上面程序,返回下面结果:

Name of the file:  foo.txt
Closed or not :  False
Opening mode :  wb
Name of the file:  foo.txt
Closed or not :  True
Opening mode :  wb

flush()方法的语法结构:

flush()方法刷新内部缓冲区,像标准输入输出的fflush。这类似文件的对象,无操作。

Python关闭时自动刷新文件。但是可能要关闭任何文件之前刷新数据。

语法

以下是flush()方法的语法:

fileObject.flush()

参数

  • NA

返回值

此方法不返回任何值。

例子

下面的例子显示了flush()方法的使用。

# -*- coding:utf-8 -*-
# !/usr/bin/python
#Author:Kenken Liu
#刷新内部缓冲区,像标准输入输出fflush。这可能是一些类似文件的对象,无操作
import time

#Open a file
fo = open("foo.txt","wb")
print("Name of the file: ",fo.name)
# Here it does nothing,but you chan call it with read operation.
start =  time.perf_counter()
fo.flush()
end = time.perf_counter()   #time.process_time
consume_time = end -start
print (consume_time)

# Close opend file
fo.close()

 执行上面程序,返回下面结果:

Name of the file:  foo.txt
2.000000000002e-06

fileno()方法的语法结构:

关于文件描述符:

文件描述符就是一个整形数字
每个进程默认打开 0、1、2 三个文件描述符, 新的文件描述符都是从 3 开始分配
一个文件描述符被回收后可以再次被分配 (文件描述符并不是递增的)
每个进程单独维护了一个文件描述符的集合
# -*- coding:utf-8 -*-
#!/usr/bin/python
#Author:Kenken Liu
#返回所使用的底层实现请求从操作系统I/O操作的整数文件描述符
#open a file
fo = open("foo.txt","wb")
print("Name of the file: ",fo.name)

fid = fo.fileno()
print ("File Descripter: ",fid)

#Close opend file
fo.close()

 执行上面程序,返回下面结果:

Name of the file:  foo.txt
File Descripter:  3

isatty()方法的语法结构:

如果文件已连接(与终端设备相关联)到一个tty(状)的设备,isatty()方法返回True,否则返回False。

语法

以下是isatty()方法的语法:

fileObject.isatty();

参数

  • NA

返回值

如果该文件被连接(与终端设备相关联)到一个tty(类似终端)设备此方法返回true,否则返回false。

例子

下面的例子显示了isatty()方法的使用。

#!/usr/bin/python
#Open a file
#返回true如果文件被连接到一个tty(一般)的设备,否则返回False
fo = open("foo.txt","wb")
print ("Name of the file: ",fo.name)

ret = fo.isatty()
print ("Return value: ",ret)

#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Return value:  False


next()方法的语法结构:

next()方法当一个文件被用作迭代器,典型例子是在一个循环中被使用,next()方法被反复调用。此方法返回下一个输入行,或引发StopIteration异常EOF时被命中。与其它文件的方法,如ReadLine()相结合next()方法工作不正常。然而,usingseek()将文件重新定位到一个绝对位置将刷新预读缓冲器。

语法

以下是next()方法的语法:

fileObject.next();

参数

  • NA

返回值

此方法返回下一个输入行。

例子

下面的示例演示next()方法的使用。

# -*- coding:utf-8 -*-
#!/usr/bin/python
#Author:KenKen Liu
#本函数是返回迭代子下一个元素的值,主要通过调用__next__()方法来实现的。如果default参数有设置,当下一个元素不存在时,
# 就返回default参数的值,否则抛出异常StopIteration。
#next()
L = [1,3,4]
it = iter(L)
print (next(it))
print (next(it,1))
print (next(it,1))
print (next(it,1))
print (next(it,1))

执行上面程序,返回下面结果:

1
3
4
1
1

例子2:

# -*- coding:utf-8 -*-
#!/usr/bin/python
#Author:KenKen Liu
#返回每次被调用时文件的下一行。
#合法的mode有:r、rb、r+、rb+、w、wb、w+、wb+、a、ab、a+、ab+
#在python3.x版本中,python2.x的g.next()函数已经更名为
# g.__next__(),所以只需要将g.next()换成g.__next__()就可以了。如果你觉得g.__next__()太丑,使用next(g)也能达到相同效果。
#Open a file
fo = open("foo.txt",encoding='gb18030', errors='ignore')
str = fo.read()
print(str)
#Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):

    line = next(fo,'e')
print ("Line No %d - %s" % (index, line))

# Close opend file
fo.close()

执行上面程序,返回下面结果:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
Line No 4 - e

read()方法的语法结构:

read()方法读取文件size个字节大小,如果读取命中获得EOF大小字节之前,那么它只能读取可用的字节。

语法

以下是read()方法的语法:

fileObject.read(size);

参数

  • size -- 这是可以从文件中读取的字节数。

返回值

此方法返回读取字符串中的字节数。

例子

下面的例子显示了read()方法的使用。

#!/usr/bin/python
#Open a file
fo = open("foo.txt","r+")
print ("Name of the file: ", fo.name)
#Assuming file has following 5 lines
#This is 1st line
#This is 2nd line
#This is 3rd line
#this is 4th line
#this is 5th line

line = fo.read(100)
print ("Read Line: %s" % (line))
#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

readline()方法的语法结构:

readline()方法从文件中读取一整行。尾部的换行符保持在字符串中。如果大小参数且非负,那么一个最大字节数,包括结尾的换行和不完整的行可能会返回。遇到EOF时立即返回一个空字符串。

语法

以下是readline()方法的语法:

fileObject.radline(size);

参数

  • size -- 这是可以从文件中读取的字节数。

返回值

此方法返回从文件中读取的行。

例子

下面的例子显示了readline()方法的使用。

#!/usr/bin/python
#Open a file
#从文件中读取一个完整的行。尾部换行符保持在字符串中
fo = open("foo.txt","r+")
print("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s" % (line))

line = fo.readline(5)
print ("Read Line : %s" % (line))

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: This is 1st line

Read Line : This 

readlines()方法的语法结构:

readlines()方法读取使用ReadLine()并返回包含行的列表直到EOF。如果可选sizehint参数不是读取到达EOF,全行共计约sizehint字节(可能四舍五入到内部缓冲区的大小后)被读取。

语法

以下是readlines()方法的语法:

fileObject.readlines(sizehint)

参数

  • sizehint -- 这是可以从文件中读取的字节数。

返回值

这个方法返回一个包含行的列表。

例子

下面的例子显示readlines()方法的使用。

#!/usr/bin/python
#Open a file
fo = open("foo.txt","r+")
print ("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readlines()
print ("Read Line: %s"  %(line))

line = fo.readlines(2)
print ("Read Line: %s " % (line))

#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
Read Line: [] 

seek()方法的语法结构:

seek()方法在偏移设定该文件的当前位置。参数是可选的,默认为0,这意味着绝对的文件定位,它的值如果是1,这意味着寻求相对于当前位置,

2表示相对于文件的末尾。没有返回值。需要注意的是,如果该文件被打开或者使用'a'或'A+'追加,任何seek()操作将在下次写撤消。

如果该文件只打开使用“a”的追加模式写,这种方法本质上是一个空操作,但读使能(模式'a+'),它仍然在追加模式打开的文件非常有用。

如果该文件在文本模式下使用“t”,只有tell()返回的偏移开都是合法的。使用其他偏移会导致不确定的行为。

请注意,并非所有的文件对象都是可搜索。

语法

以下是seek()方法的语法:

fileObject.seek(offset[,whence])

参数

  • offset -- 这是在文件中,读/写指针的位置。

  • whence -- 这是可选的,默认为0,这意味着绝对的文件定位,其它的值是1,这意味着寻求相对于当前位置,2表示相对于文件的末尾。

返回值

此方法不返回任何值。

例子

下面的例子显示了seek()方法的使用。

# -*- coding:utf-8 -*-
#!/usr/bin/python
#Author:KenKen Liu
"""
设置文件的当前位置
"""
fo = open("foo.txt","r+")
print ("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s " % (line))
# Again set the pointer to the beginning
fo.seek(0,1)
line = fo.readline()
print ("Read Line: %s " % (line))
#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: This is 1st line
 
Read Line: This is 2nd line

tell()方法的语法结构:

tell()方法返回的文件内的文件读/写指针的当前位置。

以下是tell()方法的语法:

fileObject.tell()

参数

  • NA

返回值

此方法返回该文件中读出的文件/写指针的当前位置。

例子

下面的例子显示了tell()方法的使用。

#!/usr/bin/python
# Open a file
fo = open("foo.txt","r+")
print ("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s" % (line))
#Get the current position of the file.
pos = fo.tell()
print ("Current Position: %d " % (pos))

#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: This is 1st line

Current Position: 18 

truncate()方法的语法结构:

truncate()方法截断该文件的大小。如果可选的尺寸参数存在,该文件被截断(最多)的大小。

大小默认为当前位置。当前文件位置不改变。注意,如果一个指定的大小超过了文件的当前大小,其结果是依赖于平台。

注意:此方法不会在当文件工作在只读模式打开。

语法

以下是truncate()方法的语法:

fileObject.truncate([size])

参数

  • size -- 如果可选参数存在,文件被截断(最多)的大小。

返回值

此方法不返回任何值。

例子

下面的例子显示 truncate()方法的使用。

#!/usr/bin/python
#截断文件的大小,如果可选的尺寸参数存在,该文件被截断(最多)大小
# Open a file
fo = open("foo.txt","r+")
print ("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s " % (line))

#Now truncate remaining file.
fo.truncate()
#Try to read file now
line = fo.readline()
print ("Read Line: %s " % (line))

#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Read Line: This is 1st line
 
Read Line: This is 2nd line

write()方法的语法结构:

write()方法把字符串str写入文件。没有返回值。由于缓存,字符串可能不实际显示文件,直到flush()或close()方法被调用。

语法

以下是write()方法的语法:

fileObject.write(str)

参数

  • str -- 这是要被写入的文件中的字符串。

返回值

此方法不返回任何值。

例子

下面的例子显示write()方法的使用。

fileObject.write(str)

参数

  • str -- 这是要被写入的文件中的字符串。

返回值

此方法不返回任何值。

例子

下面的例子显示write()方法的使用。

#!/usr/bin/python
#write()方法把字符串str写入文件。没有返回值。由于缓冲,字符串可能不实际显示文件,直到flush()或close()方法被调用。
# Open a file in write mode
fo = open("foo.txt","r+")
print ("Name of the file: ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
str = "This is 6th line"
# Write a line at the end of the file.在文件末尾写一行。
fo.seek(0,2)
line = fo.write(str)
# Now read complete file from beginning .现在从头开始阅读完整的文件。
fo.seek(0,0)
for index in range(6):
    line = next(fo)
    print ("Line No %d - %s" % (index,line))
#Close opend file
fo.close()

执行上面程序,返回下面结果:

Name of the file:  foo.txt
Traceback (most recent call last):
Line No 0 - This is 1st line
  File "F:/pythonDEV/简明python笔记/Python文件IO/File对象方法/write()把字符串str写入文件.py", line 19, in 

    line = next(fo)
StopIteration
Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th lineThis is 6th lineThis is 6th line

writelines()方法的语法结构:

writelines()方法写入字符串序列到文件,该序列可以是任何可迭代的对象产生字符串,字符串为一般列表,没有返回值。

语法

以下是writelines()方法的语法:

fileObject.writelines(sequence)

参数

  • sequence -- 这是字符串的序列。

返回值

此方法不返回任何值。

例子

下面的例子显示writelines()方法的使用。

#!/usr/bin/python
#Open a file in witre mode

fo = open("foo.txt","r+")
print("Name of the file : ",fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th linen","This is 7th line"]
#Write sequence of lines at the end of the file.
fo.seek(0,2)
line = fo.writelines(seq)
#Now read complete file from beginning
fo.seek(0,0)
for index in range(7):
    line = next(fo)
#    line = __next__(fo)
    print ("Line No %d - %s" % (index,line))
#Close opend file
fo.close()

执行上面程序,返回下面结果:

Traceback (most recent call last):
Name of the file :  foo.txt
  File "F:/pythonDEV/简明python笔记/Python文件IO/File对象方法/writelines()方法写入字符串序列到文件.py", line 19, in 
    line = next(fo)
Line No 0 - This is 1st line
StopIteration

Line No 1 - This is 2nd line

Line No 2 - This is 3rd line

Line No 3 - This is 4th line

Line No 4 - This is 5th lineThis is 6th lineThis is 6th lineThis is 6th lineThis is 6th linenThis is 7th lineThis is 6th linenThis is 7th lineThis is 6th linenThis is 7th lineThis is 6th linenThis is 7th line

 

你可能感兴趣的:(python)