Python 文件读写

  磁盘上的文件通过某个进程调用后启动为新进程,该进程的意义在于处理一些输入的数据,然后输出我们想要得到的结果,输出的方式有多种,比如输出到屏幕上,输出到网卡上进行传输,输出到文件系统的文件中,输出到数据库中等。为了实现数据的持久化存储,我们通常将输出内容存储于文件或数据库中,本文介绍使用Python从文件系统中读写文件,后文介绍数据库的操作。

1. 文件读写

1.1 读取文件

1 # read(): Read all context from file
2 fp = open('./data.txt')
3 context = fp.read()
4 fp.close()

1.2 read(), readline(), readlines()

read() ,从打开的文件对象中一次性读取所有内容,并返回字符串

readline(),从打开的文件对象中每次读取一行内容,然后读指针跳到下一行,如此完成所有内容的读入

readlines(),从打开的文件对象中一次性读取所有内容,并将内容存储到列表中,列表的一个元素为读入的一行内容

 1 # read(): Read all context from file
 2 fp = open('./data.txt')
 3 context = fp.read()
 4 fp.close()
 5 
 6 # readline(): Read one line at a time from file
 7 fp = open('./data.txt')
 8 context = fp.readline()
 9 fp.close()
10 
11 # readlines(): Read all lines from file and storte in list
12 fp = open('./data.txt')
13 context = fp.readlines()
14 fp.close()

1.3 写入文件

write() 将字符串内容写入文件

writelines() 将列表写入文件,列表中的所有元素自动合并

1 # write(): The file writen is string
2 fp = open('./wf.txt','w')
3 fp.write('w, Hello world')
4 fp.close()
5 
6 # writelines(): The file writen is list
7 fp = open('./wf.txt','w')
8 fp.writelines(['writelines','hello','world'])
9 fp.close()

1.4 关闭打开的文件句柄

计算机程序中,打开的一个文件占用一个文件句柄,每个进程所拥有的文件句柄数是有限的,并且文件句柄占用计算机资源。所以当我们处理完文件后,需及时关闭文件,在Python中,使用 close() 方法关闭打开的文件,通常使用 try..finally 或者 with..as 语句块来及时关闭处理完的文件对象。

1 # Use finally sure file is closed
2 try:
3     fp = open('./data.txt')
4     context = fp.read()
5 finally:
6     fp.close()
1 # Use with sure file is closed
2 with open('./data.txt') as fp:
3     context = fp.read()

1.5 文件读写练习

1.5.1 将文件中的所有单词首字母修改为大写

 1 def file_initial_upper(input_file, output_file):
 2     '''Change all words to uppercase
 3     input_file: string, input file path.
 4     output_file: string, output file path.
 5     '''
 6     with open(input_file, 'r') as fpi, open(output_file, 'a') as fpo:
 7         for line in fpi:
 8             upper_list = []
 9             for word in line.split():
10                 upper_list.append(word.capitalize())
11 
12             upper_str = ' '.join(upper_list) + '\n'
13             fpo.write(upper_str)
14 
15 
16 if __name__ == '__main__':
17     in_file = './in.txt'
18     out_file = './out.txt'
19     file_initial_upper(in_file,out_file)
View Code

2. 文件路径

os 模块是Python提供的处理文件路径和目录的函数

2.1 文件路径相关函数

2.1.1 os.getcwd(), 当前工作目录

>>> import os
>>> os.getcwd()
'/root/python'

2.1.2 os.path.abspath(), 返回指定路径的绝对路径

>>> import os
>>> dirname = './'
>>> os.path.abspath(dirname)
'/root/python'

2.1.3 os.listdir(), 列出指定路径下的所有文件

>>> os.listdir('/home/apache')
['.bash_logout', '.bash_profile', '.bashrc', '.viminfo', '.bash_history']

2.1.4 os.path.dirname(), 返回路径名

>>> os.path.dirname('/root/python')
'/root'

2.1.5 os.path.basename(),返回基名

>>> os.path.basename('/root/python')
'python'

2.1.6 os.path.exists(), 判断文件是否存在

>>> os.path.exists('/root/python')
True

2.1.7 os.path.isfile(), 判断是否是普通文件

>>> os.path.isfile('/root/.vimrc')
True

2.1.8 os.path.isdir(),判断是否是目录

>>> os.path.isdir('/root/')
True

2.1.9 os.path.expanduser(), 展开缩写的文件路径

>>> os.path.expanduser('~')
'/root'

2.1.10 os.path.isabs(),判断给定的路径是否为绝对路径

>>> os.path.isabs('/root')
True

2.1.11 os.path.join(),连接多个路径

>>> os.path.join('/home','zhubiao','python')
'/home/zhubiao/python'

2.2 文件路径练习

2.2.1 给一个目录,打印出该目录及其子目录下的所有文件的绝对路径

 1 #!/usr/bin/python3
 2 import os
 3 
 4 def walk(dirname):
 5     '''Print file name of the directory and subdirectory
 6     dirname: string
 7     '''
 8     if not os.path.exists(dirname):
 9         print(dirname,'is not exists')
10         return
11 
12     if os.path.isfile(dirname):
13         print(dirname)
14         return
15 
16     for name in os.listdir(dirname):
17         path = os.path.join(dirname,name)
18         if os.path.isdir(path):
19             walk(path)
20         else:
21             print(path)
22 
23 
24 if __name__ == '__main__':
25     dirname = input('Please input a directory name: ')
26     walk(dirname)
View Code
Andraw|朱标
原文地址:https://www.cnblogs.com/zhubiao/p/8657648.html