Python 官方文档:入门教程 => 点击学习
#/usr/bin/python content='''\ #这里使用''' This is a test file for Python ''' f=file('content.txt','w'
#/usr/bin/python
content='''\ #这里使用'''
This is
a test file
for Python
'''
f=file('content.txt','w') #以写的方式打开content.txt,可以创建一个空文件
f.write(content) #将content的内容写入到content.txt文件中
f.close #关闭文件
f=file('content.txt','r') #以只读的方式打开文件
line=f.read() #读出文件的内容
print line, #print这里加了一个逗号,防止python读完最后一行后自动添加一行空行
f.close()
print "\n"
f=file('content.txt') #默认以只读的方式打开
while True:
line=f.readline() #读文件的每行内容
if len(line)==0: #如果一行的长度为0,表示读完了所有的行
break #break跳出while循环
print line,
f.close()
输出结果如下:
This is
a test file
for python
This is
a test file
for python
python打开文件的方式可以为只读r , 写w,追加a。
#/usr/bin/python
content_append='''\
Append more content
into a file
'''
f=file('content.txt','a') #向content.txt文件中追加内容
f.write(content_append)
f.close
f=file('content.txt','r')
line=f.read()
print line,
输出结果如下:
This is
a test file
for python
Append more content
into a file
--结束END--
本文标题: Python学习之文件操作
本文链接: https://www.lsjlt.com/news/186219.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0