python 读取文件函数
2023-09-11 14:15:01 时间
python 读取文件函数
觉得有用的话,欢迎一起讨论相互学习~
感谢莫烦老师
详情
读取文件内容 file.read()
- 使用 file.read() 能够读取到文本的所有内容.
file= open('my file.txt','r')
content=file.read()
print(content)
""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""
按行读取 file.readline()
- 如果想在文本中一行行的读取文本, 可以使用 file.readline(), file.readline() 读取的内容和你使用的次数有关, 使用第二次的时候, 读取到的是文本的第二行, 并可以以此类推:
file= open('my file.txt','r')
content=file.readline() # 读取第一行
print(content)
""""
This is my first test.
""""
second_read_time=file.readline() # 读取第二行
print(second_read_time)
"""
This is the second line.
"""
读取所有行 file.readlines()
- 如果想要读取所有行, 并可以使用像 for 一样的迭代器迭代这些行结果, 我们可以使用 file.readlines(), 将每一行的结果存储在 list 中, 方便以后迭代.
file= open('my file.txt','r')
content=file.readlines() # python_list 形式
print(content)
""""
['This is my first test.\n', 'This is the second line.\n', 'This the third line.\n', 'This is appended file.']
""""
# 之后如果使用 for 来迭代输出:
for item in content:
print(item)
"""
This is my first test.
This is the second line.
This the third line.
This is appended file.
"""
相关文章
- Python 并行分布式框架 Celery
- Python语法基础_06.匿名函数、文件操作
- 使用Python读写文件进行图片复制(文件复制)
- python如何在一个类里面调用另一个类里面的东西?
- Google Earth Engine(GEE)——python导出 GeoTIFF 文件
- 为什么自学Python看不进去?
- python线程执行带有参数的任务(args、kwargs)
- 火遍全世界的Python,为啥这么牛?
- Python 读取 .mdb文件信息
- python “~“ 的含义
- Python 核实文件是否存在的函数
- python学习之OpenCV-Python模块的部分应用示例(生成素描图和动漫图)
- Python代码库之比较2个文件是否一致(含代码)
- Python基础入门-文件读写
- 《Python自动化运维:技术与最佳实践》一2.2 文件与目录差异对比方法
- 【转载】 解决VSCode运行或调试python文件无反应的问题
- python语言:将多张图片压成一段视频——利用opencv-python库实现
- Python Kivy安装及使用PyCharm进行简单测试(讲解如何参照kivy官方说明安装测试)
- python with as 以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。
- 【Python基础】如何向 google colab 上传文件?
- PyCharm设置Python版本
- Python遍历json文件,并更换变量
- Python 数组保存到文件