Python 文件 I/O 2018-07-31

1. 打印到屏幕:print

可以给print传递零个或多个用逗号隔开的表达式,print把传递的表达式转换成一个字符串表达式,并将结果写到标准输出:

# -*- coding: UTF-8 -*-                                          
print "Hello",",World",123
helloworld@LG-virtual-machine:~/code$ python test.py 
Hello ,World 123

2. 读取键盘输入:raw_input input

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

# -*- coding: UTF-8 -*-                                          
str = raw_input("Please input:")
print "What you input is :",str

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Please input:hello world
What you input is : hello world

2.2 input([prompt])raw_input([prompt])函数基本类似,但是input可以接收一个Python表达式作为输入,并将运算结果返回

# -*- coding: UTF-8 -*-                                          
str = input("Please input:")
print "What you input is :",str

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Please input:hello
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    str = input("Please input:")
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
  • 可以看到像往常一样输入 hello 的结果是NameError,但输入一个Python表达式则正常
helloworld@LG-virtual-machine:~/code$ python test.py 
Please input:[x*5 for x in range(2,10,2)]
What you input is : [10, 20, 30, 40]

3. 打开和关闭文件

3.1 open,首先必须用内置的open函数打开一个文件,创建一个file对象,相关方法才可以调用它进行读写
file object = open(file_name, [, access_mode][, buffering])
file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)
buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
image.png
image.png
image.png

3.2 当文件被打开后,得到的 file 对象有以下属性
file.closed: 如果文件已经被关闭,则返回true,否则返回false
file.mode:返回被打开文件的访问模式
file.name:返回文件的名称
file.softspace:如果用print输出后,必须跟一个空格符,则翻译false,否则返回true

# -*- coding: UTF-8 -*-                                          
fo = open ("a.txt",'w')
print "file name:",fo.name
print "closed or not:",fo.closed
print "access mode:",fo.mode
print "末尾是否强制加空格",fo.softspace

fo.close()
print "closed or not?",fo.closed
print "file name:",fo.name
print fo.mode

输出

helloworld@LG-virtual-machine:~/code$ python test.py 
file name: a.txt
closed or not: False
access mode: w
末尾是否强制加空格 0
closed or not? True
file name: a.txt
w

4. write()方法,

可将任何字符串写入一个打开的文件夹,Python字符串可以是二进制数据,不仅仅是文字,write()不会在字符串的结尾添加换行符

# -*- coding: UTF-8 -*-
fo = open ("a.txt",'w')
fo.write("Hello world!!!!")                                      
fo.close()
helloworld@LG-virtual-machine:~/code$ python test.py 
helloworld@LG-virtual-machine:~/code$ cat a.txt 
Hello world!!!!helloworld@LG-virtual-machine:~/code$ 

5. read()方法

从一个打开的文件中读取字符串,python字符串可以是二进制数据,不仅仅是文字,语法:
fileobject.read([count])
在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。

# -*- coding: UTF-8 -*-
fo = open ("a.txt",'r+')
#fo.write("Hello World!!!") #同时使用的话会导致read()无法读出
str = fo.read()                                                  
print str
fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Hello world!!!

6. tell()方法

返回文件内的当前位置,即,下一次读写会发生在文件开头多少字节后
seek(offset[, from])方法改变当前文件的位置,offset 表示要移动的字节数,from 变量指定开始移动字节的参考位置;如果 from 被设为0,则将文件的开头作为移动字节的参考位置;如果设为1,则使用当前的位置作为参考位置;如果设为2,则将文件的末尾作为参考位置

# -*- coding: UTF-8 -*-
fo = open ("a.txt",'r+')
str = fo.read(5)
print str

position = fo.tell()
print "current position:",position

fo.seek(0,0)
str = fo.read(5)                                                 
print str
fo.close()       

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Hello
current position: 5
Hello

7. File的其他相关方法

7.1 flush():刷新缓冲区,即将缓冲区的数据立刻写入文件,同时清空缓冲区,而不是被动地等待缓冲区写入
fileObject.flush()
进度条效果实例:

# -*- coding: UTF-8 -*-
import sys,time                                                  
for x in range(30):
    sys.stdout.write('*')
    sys.stdout.flush()
    time.sleep(0.2)
  • 其输出是每隔0.2秒输出一个*,类似于进度条,**如果没有flush()语句,将没有进度条效果,而是在最后面一次性全部输出来

7.2 next()方法在文件使用迭代器时会使用到,该方法返回文件的下一行,如果到达结尾(EOF),则出发StopIteration

# -*- coding: UTF-8 -*-                                          
fo = open("a.txt","r+")
for index in range(5):
    line = fo.next()
    print "第 %d 行 - %s"%(index, line)
fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ cat a.txt 
This is the first line
This is the second line
This is the third line
This is the forth line

helloworld@LG-virtual-machine:~/code$ python test.py 
第 0 行 - This is the first line

第 1 行 - This is the second line

第 2 行 - This is the third line

第 3 行 - This is the forth line

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    line = fo.next()
StopIteration
  • 可以看到最后触发了StopInteration,而且文本中每一行最后面有一个换行符,print又会加一个换行符,所以出现空行

7.3. readline()方法,从文件读取整行,包括'\n'字符;如果指定了一个非负的整数,则返回指定大小的字节数,包括'\n'字符

# -*- coding: UTF-8 -*-
fo = open("a.txt","r+")
line = fo.readline()
print line

line = fo.readline(5)
print line        
fo.close()       

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
This is the first line

This

next()readline()对比

# -*- coding: UTF-8 -*-
fo = open("a.txt","r+")
for x in range(10):
    line = fo.readline()
    print line
fo.close() 

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
This is the first line

This is the second line

This is the third line

This is the forth line








  • 可以看到readline()读到文件末尾的时候还会继续以空行往下读,而不会报StopIteration错误。

7.4 readlines()方法读取所有行(直到结束符EOF)并返回列表,该列表可以由Python的for ... in 结构来进行处理,碰到结束符EOF则返回None

# -*- coding: UTF-8 -*-                                          
fo = open('a.txt','r')

print fo.readlines()
fo.seek(0,0)

for line in fo.readlines():
    line = line.strip()
    print line
print fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
['This is the first line\n', 'This is the second line\n', 'This is the third line\n', 'This is the forth line\n']
This is the first line
This is the second line
This is the third line
This is the forth line
None

7.5 truncate([size])用于截断文字,如果指定了可选参数size,则表示截断文件为size个字符;如果没有指定,则从当前位置起截断,截断之后size后面的所有字符被删除

# -*- coding: UTF-8 -*-
fo = open('a.txt','r+')                                          

line = fo.readlines()
print line
fo.seek(0,0)
fo.truncate()
line = fo.readlines()
print line

fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
['This is the first line\n', 'This is the second line\n', 'This is the third line\n', 'This is the forth line\n']
[]

截取10个

# -*- coding: UTF-8 -*-                                          
fo = open('a.txt','r+')

line = fo.readlines()
print line
fo.seek(0,0)
fo.truncate(10)
line = fo.readlines()
print line

fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
['This is the first line\n', 'This is the second line\n', 'This is the third line\n', 'This is the forth line\n']
['This is th']

7.6 writelines([str])向文件中写入一序列的字符串,这一序列字符串可以是由迭代对象产生的,如一个字符串列表。换行需要制定换行符 \n。

# -*- coding: UTF-8 -*-                                          
fo = open('a.txt','r+')

seq = ['Hello\n','World\n','Python\n']
fo.writelines(seq)
fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
helloworld@LG-virtual-machine:~/code$ cat a.txt 
Hello
World
Python

7.7 问题:在write()内容后,直接read文件输出会为空?
这是因为指针已经在内容末尾,因此有2种解决方案:先close文件,open后再读取;第二是采用seek()让指针先回到文件头
问题复现:

# -*- coding: UTF-8 -*-
fo = open('a.txt','r+')

seq = ['Hello\n','World\n','Python\n']
fo.writelines(seq)                                               
print fo.read()
fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 


解决:

# -*- coding: UTF-8 -*-
fo = open('a.txt','r+')

seq = ['Hello\n','World\n','Python\n']
fo.writelines(seq)   
fo.seek(0,0) #让指针回到文件头                                            
print fo.read()
fo.close()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Hello
World
Python

8. 重命名和删除文件

Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件
8.1 rename()用来重命名,方法需要两个参数,当前的文件名和新文件名。

os.rename(current_file_name, new_file_name)

8.2 remove()方法,删除文件,需要提供要删除的文件名作为参数
os.remove(file_name)

# -*- coding: UTF-8 -*-                                          
import os
os.rename("a.txt","b.txt")

os.remove("b.txt")

8.3 mkdir()方法,在当前目录下创建新的目录
8.4 chdir()方法,改变当前的目录
8.4 getcwd()方法,显示当前的工作目录
8.4 rmdir()方法,删除目录,目录名称以参数传递,在删除这个目录之前,它的所有内容应该被清除

  1. 为了保证无论是否出错都能正确地关闭文件,我们可以使用 try ... finally 来实现
try:
    f = open('/path/to/file', 'r')
    print f.read()
finally:
    if f:
        f.close()

但是每次这么写太繁琐,所以可加入with语句来自动调用close()f方法

with open('/path/to/file', 'r') as f:
    print f.read()
posted @ 2018-08-21 20:09  默写年华  阅读(102)  评论(0编辑  收藏  举报