磁盘上的文件通过某个进程调用后启动为新进程,该进程的意义在于处理一些输入的数据,然后输出我们想要得到的结果,输出的方式有多种,比如输出到屏幕上,输出到网卡上进行传输,输出到文件系统的文件中,输出到数据库中等。为了实现数据的持久化存储,我们通常将输出内容存储于文件或数据库中,本文介绍使用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') asfpo:7 for line infpi:8 upper_list =[]9 for word inline.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(), 返回指定路径的绝对路径

>>> importos>>> 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 importos3

4 defwalk(dirname):5 '''Print file name of the directory and subdirectory6 dirname: string7 '''

8 if notos.path.exists(dirname):9 print(dirname,'is not exists')10 return

11

12 ifos.path.isfile(dirname):13 print(dirname)14 return

15

16 for name inos.listdir(dirname):17 path =os.path.join(dirname,name)18 ifos.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

python写文件字母_Python - 文件读写相关推荐

  1. 用python写wps的excel文件

    参考了网上的一些帖子,试了一下用python写wps的excel文件(需要windows操作系统,安装了wps的表格处理程序,安装了pywin32)--我安装的是WPS个人版,可以免费使用的. imp ...

  2. 使用python处理wps表格_用python写wps的excel文件 | 学步园

    参考了网上的一些帖子,试了一下用python写wps的excel文件(需要windows操作系统,安装了wps的表格处理程序,安装了pywin32)--我安装的是WPS个人版,可以免费使用的. imp ...

  3. python 写csv加锁_Python: 对CSV文件读写 和 Md5加密

    1. python 有专门的csv包,直接导入即可. import csv: 2. 直接使用普通文件的open方法 csv_reader=open("e:/python/csv_data/l ...

  4. python怎么保存文件代码_Python文件读写保存操作的实现代码

    本篇文章给大家带来的内容是关于Python文件读写保存操作的实现代码 ,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 记录下第一次使用Python读写文件的过程,虽然很简单,第一次实 ...

  5. python遍历文件对象_Python文件常见操作实例分析【读写、遍历】

    本文实例讲述了Python文件常见操作.分享给大家供大家参考,具体如下: 1.文件是什么? 文件是存储在外部介质上的数据或信息集合,程序中源程序.数据中保存的数据.图像中的像素数据等等: 文件是有序的 ...

  6. python 写txt 换行_python中写入txt文件需要换行,以及\r 和\n

    在Python中,用open()函数打开一个txt文件,写入一行数据之后需要一个换行 如果直接用 f.write('\n') 只会在后面打印一个字符串'\n',而不是换行' 需要用 f.write(' ...

  7. python存文件代码_Python文件读写保存操作的示例代码

    记录下第一次使用Python读写文件的过程,虽然很简单,第一次实现其实也有些注意的事项. 单个文件的读操作: 我们先假设一个需求如下: 读取一个test.txt文件 删除指定字符之前的文本 需求明白之 ...

  8. python文件写入_python 文件读写操作

    读文件 打开一个文件用open()方法(open()返回一个文件对象,它是可迭代的): >>> f = open('test.txt', 'r') r表示是文本文件,rb是二进制文件 ...

  9. python文件创建人_Python文件处理:创建、打开、追加、读、写

    在Python中,不需要导入外部库来读取和写入文件.Python为创建.写入和读取文件提供了内置的函数. 在本文中,我们将学习 如何创建文本文件 如何将数据附加到文件中 如何读取文件 如何逐行读取文件 ...

最新文章

  1. 由event target引发的关于事件流的一连串思考(二)
  2. linux系统硬盘数据恢复软件下载,Linux硬盘数据恢复软件
  3. #论文 《Deep Residual Learning for Image Recognition》
  4. ifm management of technology q and a session 2
  5. c语言贪吃蛇游戏完整代码
  6. myclipes 配置php,myclipse使用技巧
  7. 苹果如何分屏_刚刚,苹果证实,iPhone12 刘海没了!
  8. Docker基础学习笔记02:Docker基本操作
  9. MyBatis框架笔记02:接口方式使用MyBatis
  10. 数据库减压--php+mysql+memcached模拟nosql
  11. Unity3D基础18:物体查找与控制
  12. Webservice检查
  13. Linux使用yum安装JDK
  14. 【PaddleHub模型贡献】一行代码实现海洋生物识别
  15. laravel 先判断在加查询条件,whereBetween,whereIn
  16. 如何应对VB中对象库注册失败(MSCOMCTL.OCX)
  17. Itext中强行调整行高缩小行间距
  18. 西南大学考研计算机808真题和复试
  19. ubuntu18.04上的draftsight 2D的安装
  20. win7--svchost占用内存过大

热门文章

  1. Linux下c语言模拟贝壳物联设备在线
  2. 7-21 输出大写英文字母 (15分)
  3. win7连接sftp_WinSCP(SFTP客户端)官方版下载_WinSCP(SFTP客户端) v5.17.7.10640中文版 - Win7旗舰版...
  4. 几款视频剪辑软件,轻松完成视频转换,剪辑
  5. 专业测评:iphone7致命缺陷曝光
  6. vue 项目中实现按钮防抖
  7. Java实现对文件的增删改查操作
  8. 启动RocketMQ报错:Please set the JAVA_HOME variable in your environment, We need java 64
  9. 滴滴实时计算发展之路及平台架构实践
  10. GetLastError函数封装显示具体错误信息