python入门-文件

1 读取文件

with open('1.txt') as file_ojbect:
    contents = file_ojbect.read()
    print(contents.rstrip())

 with 自动体会文件的关闭  

open 打开文件,然后返回一个文件对象

把结果放到变量中,然后打印去掉右边空行的变量

其他几个 读取文件的用法

with open('1.txt') as file_ojbect:
    for line in file_ojbect:
        print(line.rstrip())



filename = '1.txt'
with open(filename) as file_ojbect:
    lines = file_ojbect.readlines()

for line in lines:
    print(line.rstrip())


filename = '1.txt'
with open(filename) as file_ojbect:
    lines = file_ojbect.readlines()

pi_string=''
for line in lines:
    pi_string +=line.strip()

print(pi_string)
print(len(pi_string))

2 写入文件

filename = '3.txt'
with open(filename,'w') as file_ojbect:
    file_ojbect.write("I love programming.
")
    file_ojbect.write("I love creating new games.
")

打开 文件 然后写入如下内容

3 追加文件

filename = '3.txt'
with open(filename,'a') as file_ojbect:
    file_ojbect.write("I love studying.
")
    file_ojbect.write("I love playing games.
")

打开文件 然后追加如下内容

原文地址:https://www.cnblogs.com/baker95935/p/9437609.html