Python学习笔记(10)-文件、目录和输入输出操作

读取键盘的输入

Python提供了input()内置函数从标准输入读入一行文本,默认的标准输入是键盘。input可以接收一个Python表达式作为输入,并将运算结果返回,如下所示:

1
2
3
4
5
6
7
8
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

文件目录的斜杠处理

在Python中,\是转义字符的标志,如下所示:

1
print("Hello, \npython")

运行结果如下所示:

1
2
Hello,
python

如果文件目录的首字母有n,那么就容易出错,如下所示:

1
print("c:\nowhere")

运行结果如下所示:

1
2
c:
owhere

目录的处理方法之一加r

此时可以在目录前面加一个r,如下所示:

1
print(r"c:\nowhere")

运行结果如下所示:

1
c:\nowhere

目录的处理方法之二加双斜杠\\

加双斜杠\\其实就是把\进行转义,如下所示:

1
print("c:\\nowhere")

运行结果如下所示:

1
c:\nowhere

末尾左斜杠的处理

但是还要注意的是,如果目录后面还有\,上面的两种方式就不合适了,如下所示:

1
print(r"c:\nowhere\")

运行结果如下所示:

1
2
3
4
File "<ipython-input-8-2406b3e40ced>", line 1
print(r"c:\nowhere\")
^
SyntaxError: EOL while scanning string literal

运行出错,EOL是End-of-life(项目终止/停产)的缩写。此时位于末尾的左斜杠的前面应该再加一个左斜杠,并用引号隔开,如下所示:

1
print(r"c:\nowhere" "\\")

运行结果如下所示:

1
c:\nowhere\

文件对象的方法

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被忽略了或者为负,那么该文件的所有内容都将被读取并且返回,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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()会从文件中读取单独的一行,换行符为\nf.readline()如果返回一个空字符串,说明已经读取到了最后一下,看下面的案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
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,则读取指定长度的字节,并且将这些字节按行分割,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
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']

另外一种读取文件内容的方式就是对文件中的行进行迭代,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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写入到文件中,然后返回写入的字符数,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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!

如果要写入一些非字符串的东西, 那么将需要先进行转换,如下所示:

1
2
3
4
5
6
7
8
9
10
11
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表示文件的结尾,例如:

  1. seek(x,0):从起始位置即文件首行首字符开始移动x个字符
  2. seek(x,1):表示从当前位置往后移动x个字符
  3. seek(-x,2):表示从文件的结尾往前移动x个字符
  4. from_what值为默认为0,即文件开头。

看下面的案例:

1
2
3
4
5
6
7
8
9
10
11
>>> 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()来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常,如下所示:

1
2
3
4
5
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: read of closed file

当处理一个文件对象时,使用with关键字是非常好的方式。在结束后,它会帮你正确的关闭文件,如下所示:

1
2
3
4
5
6
>>> with open('foo.txt','r') as f:
... read_data = f.read()
...
>>>
>>> f.closed
True

参考资料

  1. 菜鸟教程
  2. MagnusLieHetland. Python基础教程.第3版[M]. 人民邮电出版社, 2018.