0
点赞
收藏
分享

微信扫一扫

Python学习-文件的基本操作

天悦哥 2024-11-06 阅读 14

text = "write a text\nHello word"
print (text)
'''
结果为:
write a text
Hello word
'''

my_file = open("file1.txt","w")  #以写入方式创建文件,如果文件不存在就在当前目录创建
my_file.write(text)
my_file.close()


with open("file2.txt","w") as f2: #清空文件,然后写入
    f2.write("Python\nVery good!")


with open("file2.txt","a") as f2:  #在文件后面增加内容
    f2.write(text)

with open("file2.txt","r") as f2:  #以读取方式打开文件
    content = f2.read()  #读取全部内容
    print(content)
'''
结果为:
Python
Very good!write a text
Hello word
'''


with open("file2.txt","r") as f2:  #以读取方式打开文件
    content = f2.readline()  #读取第一行内容
    print(content)
'''
结果为:
Python
'''

with open("file2.txt","r") as f2:  #以读取方式打开文件
    content = f2.readlines()  #读取所有行内容存放在一个列表中
    print(content)
'''
结果为
['Python\n', 'Very good!write a text\n', 'Hello word']
'''

fileName = "file2.txt"
with open (fileName) as f:
    for line in f:
        print(line.rstrip())
'''
结果为:
Python
Very good!write a text
Hello word
'''

举报

相关推荐

0 条评论