Python文件读的几种方式

版权声明: https://blog.csdn.net/qq_37457432/article/details/87942081

Python文件读写的几种方式之读的方式

#最简单粗暴 无关闭流 不推荐
print(open("file.txt").read())

#正常读取文件,在使用后关闭
file=open("file.txt")
print(file.read())
file.close()

#with的用法,用后即关闭
#open打开文件存储到file_reader中
with open("file.txt") as file_reader:
    contents=file_reader.read()
    print(contents)

#一行一行的打印
with open("file.txt") as file_reader2:
    for line in file_reader2:
        print(line)
        print("--------------------")


#从文件读取行,并且存到列表中
lines=[]

with open("file.txt") as file_reader3:
    for linee in file_reader3:
        lines.append(linee)

print(lines)

以上代码均可以打开文件,本例子txt文件与源代码在同一个目录下

猜你喜欢

转载自blog.csdn.net/qq_37457432/article/details/87942081
今日推荐