Python_按⾏读取及写⼊txt 读取指定单⾏:
#读取单⾏⽂本
def file_read(line_target):#传⼊的参数为要获取⽂本的⽬标⾏数
with open('', 'r',encoding='utf-8') as file:#打开指定⽂本⽂件
for num, line in enumerate(file):#num从0开始循环,所以对应的⾏数要减⼀
if num == line_target-1:#当⾏数循环到等于传⼊的参数值减⼀时,返回这⼀⾏的⽂本内容并跳出循环
return line
break
⼀次读取所有⽂本并按⾏赋值到列表:
SaveList=[]#存档列表
#读取⽂本内容到列表
with open("","r",encoding='utf-8') as file:
for line in file:
line=line.strip('\n')#删除换⾏符
SaveList.append(line)
file.close()
把列表⾥的元素按⾏写⼊⽂本⽂件:
#写⼊存档到⽂件
with open("","w",encoding='utf-8') as file:
python怎么读取txtfor i in SaveList:
file.write(i+'\n')
file.close()
以追加⽽不是覆盖的⽅式在⽂件末尾写⼊⾏:
with open("","a",encoding='utf-8') as file:
file.write("⽂本内容\n")
file.close()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。