python文件读取

Posted i青春

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python文件读取相关的知识,希望对你有一定的参考价值。

‘‘‘
文件读取

‘‘‘
# python通过内置open()方法打开文件,若文件存在,则打开并进行读取操作,
# 否则创建文件,相关参数有w, w+, a, a+
if "hello.txt" is True:
# 文件打开时,指定编码方式
file = open("hell.txt",‘r‘,encoding=‘utf-8‘)
res = file.read() # 读取文件,可在read()方法中写入需要读取的字符长度
file.close() # 文件打开后,需要及时关闭,以免对文件造成不必要的损坏
print(res)
file = open("hell.txt",‘w‘,encoding=‘utf-8‘)
file.close()

# 使用with语句打开文件
with open("hello.txt","w",encoding="utf-8") as f: # w 清空原来内容,覆盖写入,a 在原本基础上追加写入
f.write("今天是个好日子")
f.flush() # 写入文件后,如果不想立刻关闭文件可以通过 flush()方法将缓存区内容写入文件
f.close() # 往文件写入内容之后,一定要调用close()方法,否则写入的内容不会保存到文件中。

with open("hello.txt","r",encoding=‘utf-8‘) as f1:
# f1.seek(6) # 移动指针位置
result = f1.read(3)
result1 = f1.readline() # 使用read()方法读取文件时,如果文件比较大,一次性读取所有内容,占用内存比较大,
# 所以会采用逐行读取的方式
f1.close()
print(result1)

# with open("helloword.txt","w",encoding="utf-8") as f2:
# f2.write("hello.txt")
# f2.close()

with open("helloword.txt","r",encoding="utf-8")as f3:
num = 0
while True:
num += 1
line = f3.readline()
if line == ‘‘:
break
# f3.close()
print(num,line,end=‘ ‘)
print("="*20 + "读取全部行" + "="*20)

with open("helloword.txt","r") as f4:
result2 = f4.readlines()
for item in result2:
print(item)

以上是关于python文件读取的主要内容,如果未能解决你的问题,请参考以下文章

python中怎么读取文件内容

Python3读取大文件的方法

python 读取日志文件

python读取较大数据文件

python读取较大数据文件

python 读取文件