2017/6/9-Python文件读写的方法
来源:互联网 发布:琉璃神社app备用域名 编辑:程序博客网 时间:2024/06/03 17:58
# 使用斜杠“/”: "c:/test.txt"… 不用反斜杠就没法产生歧义了 # 将反斜杠符号转义: "c:\\test.txt"… 因为反斜杠是转义符,所以两个"\\"就表示一个反斜杠符号 # file=open('D:\\jupyter\\test.txt')##file=open('D:/jupyter/test.txt')#file=open('test.txt')#和程序在一个同一路径下file=open('test.txt')file.read()
'hi quincyqiang\nhow are you'
#模式描述# http://www.yiibai.com/python3/python_files_io.html# 读文件有3种方法:read()将文本文件所有行读到一个字符串中。 # readline()是一行一行的读 # readlines()是将文本文件中所有行读到一个list中,文本文件每一行是list的一个元素。 # 优点:readline()可以在读行过程中跳过特定行。 \#第一种方法file_1=open('test.txt')file_2=open('output.txt','w')while True: line=file_1.readline() print(line.strip())#取出换行 file_2.write(line) if not line: breakfile_2.close()
hi quincyqianghow are you
#第二种方法,使用for循环file_2=open('output.txt','w')for line in open('test.txt'): print(line.strip()) file_2.write(line)file_2.close()
hi quincyqianghow are you
#第三种方法文件上下文文件上下文管理器 with open('somefile.txt', 'r') as f: data = f.read() # Iterate over the lines of the file with open('somefile.txt', 'r') as f: for line in f: # process line # Write chunks of text data with open('somefile.txt', 'w') as f: f.write(text1) f.write(text2) ... # Redirected print statement with open('somefile.txt', 'w') as f: print(line1, file=f) print(line2, file=f)
阅读全文
0 0
- 2017/6/9-Python文件读写的方法
- Python读写文件的方法
- [Python]读写文件方法
- PYTHON读写xml文件的方法
- python中读写csv文件的方法
- Python文件的读写
- python文件的读写
- Python 文件的读写
- python文件的读写
- Python文件的读写
- Python的读写文件
- 【Python】文件的读写
- python文件的读写
- python使用xlrd模块读写Excel文件的方法
- python使用xlrd模块读写Excel文件的方法
- Python文件读写+创建临时文件夹的基本方法
- Python遍历文件夹和读写文件的方法
- Python遍历文件夹和读写文件的方法
- Python爬虫系列(七)豆瓣图书排行榜(数据存入到数据库)
- 2017/6/8-python正则表达式的使用
- redis中修改密码
- VUE 生命周期图示
- Python基础学习(八)
- 2017/6/9-Python文件读写的方法
- Go Reflect
- Vue实现百度下拉提示搜索
- Swift调用OC第三方框架
- Laravel-博客实战+踩坑
- 安装es_bug
- 深度学习实战-使用Kera预测人物年龄
- 好东西
- 通过递归的矩阵向量空间预测组合语义