Python自学笔记006-对文件的操作

换行\n

text='First line.\nSecond line.\nLast line.'
print(text)

输出如下:

First line.
Second line.
Last line.

\t tab对齐

在需要实现tab对齐的行的开头加上\t即可实现。

open

open(‘文件路径’,’打开方式’)
打开方式有以下几种(仅列出常用方式):

  • ‘r’:只读,文件指针在文件开头。
  • ‘r+’:读写,文件指针在开头。
  • ‘w’:只写,如果文件存在则打开文件,并从头开始编辑,原有内容会被删除;若文件不存在,则创建新文件。
  • ‘w+’:读写。其余同上。
  • ‘a’:追加。若文件存在,则指针在文件结尾;若不存在,创建新文件进行写入。
  • ‘a+’:读写,其余同上。
text='First line.\nSecond line.\nLast line.'

my_file=open('test1.txt','w')
my_file.write(text)
my_file.close()  #注意一定要关闭才能成功写入

给文件增添内容

使用’a’打开方式来对文件进行追加。

text='\tFirst line.\n\tSecond line.\n\tLast line.'

my_file=open('test1.txt','a')
my_file.write('\nThis is the appended line.')
my_file.close()

修改后的文件内容:

First line.
Second line.
Last line.
This is the appended line.

读取文件内容 file.read()

# 读取文件全部内容
file=open('test1.txt','r')
text=file.read()
print(text)

输出如下:

First line.
Second line.
Last line.
This is the appended line.

按行读取 file.readline()

读取第几次就是第几行

# 按行读取
file=open('test1.txt','r')
text1=file.readline()
print('text1:',text1)

text2=file.readline()
print('text2:',text2)

输出如下:

text1: First line.

text2: Second line.

读取所有行file.readlines()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值