读取键盘的输入
Python提供了input()内置函数从标准输入读入一行文本,默认的标准输入是键盘。input可以接收一个Python表达式作为输入,并将运算结果返回,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat input.py
#!/usr/bin/python3
str=input("Please input: ")
print("What you input is: ",str)
biotest@biotest-VirtualBox:~/python3/03file$ python3 input.py
Please input: Hello
What you input is: Hello
文件的读取
open()将会返回一个file对象,基本语法格式为open(filename,mode),其中filename:包含了你要访问的文件名称的字符串值。mode决定了打开文件的模式,打开文件的模式有:①只读;②写入;③追加。这个参数是非强制的,默认文件访问模式为只读(r)。不同模式打开文件的完全列表:
模式
描述
r
以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb
以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。
r+
打开一个文件用于读写。文件指针将会放在文件的开头。
rb+
以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w
打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb
以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+
打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+
以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a
打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+
打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
下图总结了这几种模式(出处:菜鸟教程):
[图片上传失败...(image-895a1-1551584864578)]
模式
r
r+
w
w+
a
a+
读
+
+
+
+
写
+
+
+
+
+
创建
+
+
+
+
覆盖
+
+
指针在开始
+
+
+
+
指针在结尾
+
+
文件读写案例
下面的代码会将一些字符串写入到文件foo.txt中,代码如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat write.py
#!/usr/bin/python3
# open a file
# If this file does not exist, python will create it
# You can use absolute path or current path;
f = open("foo.txt","w")
f.write("Python is a good program language.\n Yes, it is very good!\n")
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 write.py
biotest@biotest-VirtualBox:~/python3/03file$ ls
foo.txt input.py write.py
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
代码解释:open()括号中是文件路径,如果不指明绝对路径,则就会默认为当前目录;如果文件存在,就打开,如果不存在,代码会创建这个文件。
文件对象的方法
file对象常用函数
file对象使用open函数来创建,下表列出了file对象常用的函数:
序号
方法及描述
1
file.close():关闭文件。关闭后文件不能再进行读写操作。
2
file.flush():刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
3
file.fileno():返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。
4
file.isatty():如果文件连接到一个终端设备返回 True,否则返回 False。
5
file.next():返回文件下一行。
6
file.read([size]):从文件读取指定的字节数,如果未给定或为负则读取所有。
7
file.readline([size]):读取整行,包括 "\n" 字符。
8
file.readlines([sizeint]):读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。
9
file.seek(offset[, whence]):设置文件当前位置
10
file.tell():返回文件当前位置。
11
file.truncate([size]):从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。
12
file.write(str):将字符串写入文件,没有返回值。
13
file.writelines(sequence):向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。
f.read()
为了读取一个文件的内容,调用f.read(size),这将读取一定数目的数据,然后作为字符串或字节对象返回。size是一个可选的数字类型的参数。当size被忽略了或者为负,那么该文件的所有内容都将被读取并且返回,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
biotest@biotest-VirtualBox:~/python3/03file$ cat read.py
#!/usr/bin/python3
# open a file
f = open("foo.txt","r")
str=f.read()
print(str)
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 read.py
Python is a good program language.
Yes, it is very good!
f.readline()
f.readline()会从文件中读取单独的一行,换行符为\n,f.readline()如果返回一个空字符串,说明已经读取到了最后一下,看下面的案例:
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
biotest@biotest-VirtualBox:~/python3/03file$ cat readline.py
#!/usr/bin/python3
f=open("foo.txt","r")
str=f.readline()
print(str)
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 readline.py
Python is a good program language.
f.readlines()
f.readlines()将返回该文件中包含的所有行。如果设置可选参数sizehint,则读取指定长度的字节,并且将这些字节按行分割,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
biotest@biotest-VirtualBox:~/python3/03file$ cat readlines.py
#!/usr/bin/python3
f = open("foo.txt","r")
str=f.readlines()
print(str)
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 readlines.py
['Python is a good program language.\n', ' Yes, it is very good!\n']
另外一种读取文件内容的方式就是对文件中的行进行迭代,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
biotest@biotest-VirtualBox:~/python3/03file$ cat iteration.py
#!/usr/bin/python3
f=open("foo.txt","r")
for line in f:
print(line,end=" ")
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 iteration.py
Python is a good program language.
Yes, it is very good!
f.write()
f.write(string)会将string写入到文件中,然后返回写入的字符数,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good program language.
Yes, it is very good!
biotest@biotest-VirtualBox:~/python3/03file$ cat f_write.py
#!/usr/bin/python3
f = open("foo.txt","w")
num = f.write("Python is a good tool.\n Yes, it is good!\n")
print(num)
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 f_write.py
41
biotest@biotest-VirtualBox:~/python3/03file$ cat foo.txt
Python is a good tool.
Yes, it is good!
如果要写入一些非字符串的东西, 那么将需要先进行转换,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat string_trans.py
#!/usr/bin/python3
f = open("foo1.txt","w")
value = ('www.runoob.com',14)
s = str(value)+"\n"
f.write(s)
f.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 string_trans.py
biotest@biotest-VirtualBox:~/python3/03file$ cat foo1.txt
('www.runoob.com', 14)
f.tell()
f.tell()返回文件对象当前所处的位置,它是从文件开头开始算起的字节数。
f.seek()
如果要改变文件当前的位置,可以使用f.seek(offset,from_what)函数。
from_what的值,如果是0表示开头,如果是1表示当前位置,2表示文件的结尾,例如:
seek(x,0):从起始位置即文件首行首字符开始移动x个字符
seek(x,1):表示从当前位置往后移动x个字符
seek(-x,2):表示从文件的结尾往前移动x个字符
from_what值为默认为0,即文件开头。
看下面的案例:
>>> f=open('foo.txt','rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)
5
>>> f.read(1)
b'5'
>>> f.seek(-3,2)
38
>>> f.read(1)
b'd'
f.close()
在文本文件中(那些打开文件的模式下没有b的),只会相对于文件起始位置进行定位。当你处理完一个文件后,调用f.close()来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常,如下所示:
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "", line 1, in
ValueError: read of closed file
当处理一个文件对象时,使用with关键字是非常好的方式。在结束后,它会帮你正确的关闭文件,如下所示:
>>> with open('foo.txt','r') as f:
... read_data = f.read()
...
>>>
>>> f.closed
True
pickle模块
python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。基本接口如下所示:
pickle.dump(obj, file, [,protocol])
有了 pickle 这个对象, 就能对 file 以读取的形式打开,即x = pickle.load(file0)。file表示类文件对象,它有read()和readline()接口,看下面的案例:
biotest@biotest-VirtualBox:~/python3/03file$ cat pickly.py
#!/usr/bin/python3
import pickle
# using pickle module to save data object to a file
data1 = {'a':[1,2.0,3,4+6j],
'b':('string',u'Unicode string'),
'c':None}
selfref_list = [1,2,3]
selfref_list.append(selfref_list)
output = open('data.pkl','wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1,output)
# Pickle th elist using the highest protocol available.
pickle.dump(selfref_list,output,-1)
output.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 pickly.py
biotest@biotest-VirtualBox:~/python3/03file$ ls
data.pkl foo.txt input.py pickly.py readline.py read.py string_trans.py
foo1.txt f_write.py iteration.py __pycache__ readlines.py seek.py write.py
在当前目录下生成了一个data.pkl文件,打开后是乱码,现在不清楚这个文件什么意思,接着还有一段代码,如下所示:
biotest@biotest-VirtualBox:~/python3/03file$ cat pickle2.py
#!/usr/bin/python3
import pprint, pickle
pkl_file = open('data.pkl','rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
biotest@biotest-VirtualBox:~/python3/03file$ python3 pickle2.py
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
[1, 2, 3, ]
上述代码解释:
目录操作
Python中的目录操作有这些:
序号
方法及描述
1
os.access(path, mode):检验权限模式
2
os.chdir(path):改变当前工作目录
3
os.chflags(path, flags):设置路径的标记为数字标记。
4
os.chmod(path, mode):更改权限
5
os.chown(path, uid, gid):更改文件所有者
6
os.chroot(path):改变当前进程的根目录
7
os.close(fd):关闭文件描述符 fd
8
os.closerange(fd_low, fd_high):关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略
9
os.dup(fd):复制文件描述符 fd
10
os.dup2(fd, fd2):将一个文件描述符 fd 复制到另一个 fd2
11
os.fchdir(fd):通过文件描述符改变当前工作目录
12
os.fchmod(fd, mode):改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
13
os.fchown(fd, uid, gid):修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
14
os.fdatasync(fd):强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息。
15
os.fdopen(fd[, mode[, bufsize]]):通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
16
os.fpathconf(fd, name):返回一个打开的文件的系统配置信息。name为检索的系统配置的值,它也许是一个定义系统值的字符串,这些名字在很多标准中指定(POSIX.1, Unix 95, Unix 98, 和其它)。
17
os.fstat(fd):返回文件描述符fd的状态,像stat()。
18
os.fstatvfs(fd):返回包含文件描述符fd的文件的文件系统的信息,像 statvfs()
19
os.fsync(fd):强制将文件描述符为fd的文件写入硬盘。
20
os.ftruncate(fd, length):裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小。
21
os.getcwd():返回当前工作目录
22
os.getcwdu():返回一个当前工作目录的Unicode对象
23
os.isatty(fd):如果文件描述符fd是打开的,同时与tty(-like)设备相连,则返回true, 否则False。
24
os.lchflags(path, flags):设置路径的标记为数字标记,类似 chflags(),但是没有软链接
25
os.lchmod(path, mode):修改连接文件权限
26
os.lchown(path, uid, gid):更改文件所有者,类似 chown,但是不追踪链接。
27
os.link(src, dst):创建硬链接,名为参数 dst,指向参数 src
28
os.listdir(path):返回path指定的文件夹包含的文件或文件夹的名字的列表。
29
os.lseek(fd, pos, how):设置文件描述符 fd当前位置为pos, how方式修改: SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始. 在unix,Windows中有效
30
os.lstat(path):像stat(),但是没有软链接
31
os.major(device):从原始的设备号中提取设备major号码 (使用stat中的st_dev或者st_rdev field)。
32
os.makedev(major, minor):以major和minor设备号组成一个原始设备号
33
os.makedirs(path[, mode]):递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。
34
os.minor(device):从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。
35
os.mkdir(path[, mode]):以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。
36
os.mkfifo(path[, mode]):创建命名管道,mode 为数字,默认为 0666 (八进制)
37
os.mknod(filename[, mode=0600, device]):创建一个名为filename文件系统节点(文件,设备特别文件或者命名pipe)。
38
os.open(file, flags[, mode]):打开一个文件,并且设置需要的打开选项,mode参数是可选的
39
os.openpty():打开一个新的伪终端对。返回 pty 和 tty的文件描述符。
40
os.pathconf(path, name):返回相关文件的系统配置信息。
41
os.pipe():创建一个管道. 返回一对文件描述符(r, w) 分别为读和写
42
os.popen(command[, mode[, bufsize]]):从一个 command 打开一个管道
43
os.read(fd, n):从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串。
44
os.readlink(path):返回软链接所指向的文件
45
os.remove(path):删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。
46
os.removedirs(path):递归删除目录。
47
os.rename(src, dst):重命名文件或目录,从 src 到 dst
48
os.renames(old, new):递归地对目录进行更名,也可以对文件进行更名。
49
os.rmdir(path):删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
50
os.stat(path):获取path指定的路径的信息,功能等同于C API中的stat()系统调用。
51
os.stat_float_times([newvalue]):决定stat_result是否以float对象显示时间戳
52
os.statvfs(path):获取指定路径的文件系统统计信息
53
os.symlink(src, dst):创建一个软链接
54
os.tcgetpgrp(fd):返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组
55
os.tcsetpgrp(fd, pg):设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg。
56
os.tempnam([dir[, prefix]]):Python3 中已删除。返回唯一的路径名用于创建临时文件。
57
os.tmpfile():Python3 中已删除。返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除。
58
os.tmpnam():Python3 中已删除。为创建一个临时文件返回一个唯一的路径
59
os.ttyname(fd):返回一个字符串,它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联,则引发一个异常。
60
os.unlink(path):删除文件路径
61
os.utime(path, times):返回指定的path文件的访问和修改的时间。
62
os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]]):输出在文件夹中的文件名通过在树中游走,向上或者向下。
63
os.write(fd, str):写入字符串到文件描述符 fd中. 返回实际写入的字符串长度
目录操作的函数太多,用到的时候再学习,下面只列出几个简单的案例:
显示某文件夹下的所有文件名
代码如下:
C:\Users\20161111>type practice.py
import os
for filename in os.listdir('d:/Software'):
print(filename)
C:\Users\20161111>python practice.py
office_tools
Professional_tools
ProgramTool
SnapGene 3.2.1 Win
system_enhance
windows_iso
谷歌批量翻译
创建某个目录
>>> import os
>>> os.mkdir("d:/Software/test")
>>> exit()
C:\Users\20161111>d:
D:\>cd software
D:\software>dir
Volume in drive D is 新加卷
Volume Serial Number is C0C6-2E4F
Directory of D:\software
2018/05/24 09:33
2018/05/24 09:33
2018/05/08 13:46
2018/05/21 10:30
2018/05/08 13:46
2017/11/22 20:21
2018/05/13 21:38
2018/05/24 09:33
2018/05/11 00:48
2017/11/02 10:52
1 File(s) 0 bytes
10 Dir(s) 49,307,074,560 bytes free
删除某个文件夹
命令rmdir,如下所示:
>>> import os
>>> os.rmdir('d:/Software/test')
>>> exit()
D:\software>dir
Volume in drive D is 新加卷
Volume Serial Number is C0C6-2E4F
Directory of D:\software
2018/05/25 12:40
2018/05/25 12:40
2018/05/08 13:46
2018/05/21 10:30
2018/05/08 13:46
2017/11/22 20:21
2018/05/13 21:38
2018/05/11 00:48
2017/11/02 10:52
1 File(s) 0 bytes
9 Dir(s) 48,131,309,568 bytes free
把D:\Software\test这个文件夹删除了 。
对待定文件的操作
如果要对特定类型的文件进行操作时,需要用fnmatch模块,这个模块的主要作用是文件名称的匹配,并且匹配的模式使用的unix shell风格。字面意思感觉就是filename match ,以下是显示.txt文件的内容和.exe文件的文件名,其中*表示任意字符,而?只表示一个字符,如下所示: