读写文件 1

mac2024-05-24  33

 

 

\n 换行命令 

定义 text 为字符串, 并查看使用 \n 和不适用 \n 的区别:

使用 \t 能够达到 tab 对齐的效果:

>>> text = 'test hello hahhahaha secondl line. third' >>> print(text) test hello hahhahaha secondl line. third >>> text = 'test hello hahhahaha\n secondl line. \nthird' >>> print(text) test hello hahhahaha secondl line. third >>> text = '\ttest hello hahhahaha\n secondl line. \n\tthird' >>> print(text) test hello hahhahaha secondl line. third >>>

open 读文件方式 

使用 open 能够打开一个文件, open 的第一个参数为文件名和路径 ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w 为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt

>>> # -*- coding:UTF-8 -*- ... my_file = open('test.txt','w') #用法: open('文件名','形式'), 其中形式有'w':write;'r':read. >>> text = 'Python 2.7.16 |Anaconda, Inc.' >>> my_file.write(text) >>> my_file.close() >>>

 

最新回复(0)