python-读写文本数据

5.1 可以使用open函数,配合rt参数
### 读取文件并加载成一行string
>>> with open('test.txt','rt') as f:
...     data = f.read()
...
>>>
>>> data
'111\n222\n333\n\n'
### 读取文件中的每一行
>>> with open('test.txt','rt') as f:
...     for line in f:
...         print(line)
...
111

222

333

  • 类似可以使用wt参数对文件进行写入操作,类似shell的 echo > 会抹去源数据
>>> with open('test.txt','wt') as f:
...     f.write("ttt")
...     f.write("yyy")
>>> with open('test.txt','rt') as f:
...     f.read()
'tttyyy'
>>> with open('test.txt','wt') as f:
...     print('wt',file=f)
>>> with open('test.txt','rt') as f:
...     f.read()
'wt\n'
>>>
  • 如果要在文件末尾追加数据,则可以使用at参数
  • 如果要给文件使用其它的编码模式,则可以增加encoding参数
>>> with open('test.txt','rt',encoding='latin-1') as f:
...
  • 这里我们可以不使用with,使用with是因为with open在程序结束后会自动close file
  • 如果不使用with 是要注意close文件
>>> f = open('test.txt','rt')
>>> data=f.read()
>>> f.close()
>>> data
'wt\n'
>>>

相关推荐

  1. python-文本数据

    2024-04-23 10:02:02       34 阅读
  2. python文件

    2024-04-23 10:02:02       41 阅读
  3. Python文件

    2024-04-23 10:02:02       35 阅读
  4. Python 文件

    2024-04-23 10:02:02       24 阅读
  5. Python--文件

    2024-04-23 10:02:02       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 10:02:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 10:02:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 10:02:02       82 阅读
  4. Python语言-面向对象

    2024-04-23 10:02:02       91 阅读

热门阅读

  1. 从零手写 tomcat

    2024-04-23 10:02:02       55 阅读
  2. STM32 ST-LINK

    2024-04-23 10:02:02       78 阅读
  3. QML与C++交互

    2024-04-23 10:02:02       38 阅读
  4. 每日一题:Spring MVC 的执行流程是什么❓

    2024-04-23 10:02:02       41 阅读
  5. 【LeetCode热题100】【图论】课程表

    2024-04-23 10:02:02       149 阅读
  6. Linux bond0 配置方法

    2024-04-23 10:02:02       32 阅读
  7. 【C++提高】算法

    2024-04-23 10:02:02       26 阅读
  8. 7-17 KMP模式匹配算法

    2024-04-23 10:02:02       22 阅读
  9. rabbitmq 之 无法自动创建队列的问题

    2024-04-23 10:02:02       34 阅读
  10. pandas

    2024-04-23 10:02:02       34 阅读