文件的翻开的两种体式格局
f = open("data.txt","r") #设置文件对象 f.close() #封闭文件 #为了轻易,防止遗忘close掉这个文件对象,能够用下面这类体式格局替换 with open('data.txt',"r") as f: #设置文件对象 str = f.read() #可所以随意对文件的操纵
对文件的一些简朴的操纵:
一、读文件
1、简朴的将文件读取到字符串中
f = open("data.txt","r") #设置文件对象 str = f.read() #将txt文件的一切内容读入到字符串str中 f.close() #将文件封闭
2、按行读取全部文件
#第一种要领 f = open("data.txt","r") #设置文件对象 line = f.readline() line = line[:-1] while line: #直到读取完文件 line = f.readline() #读取一行文件,包含换行符 line = line[:-1] #去掉换行符,也能够不去 f.close() #封闭文件 #第二种要领 data = [] for line in open("data.txt","r"): #设置文件对象并读取每一行文件 data.append(line) #将每一行文件加入到list中 #第三种要领 f = open("data.txt","r") #设置文件对象 data = f.readlines() #直接将文件中按行读到list里,效果与要领2一样 f.close() #封闭文件
3、将文件读入数组中
import numpy as np data = np.loadtxt("data.txt") #将文件中数据加载到data数组里
二、写文件
1、简朴的将字符串写入txt中
with open('data.txt','w') as f: #设置文件对象 f.write(str) #将字符串写入文件中
2、列表写入文件
单层列表
data = ['a','b','c'] #单层列表写入文件 with open("data.txt","w") as f: f.writelines(data)
双层列表
#双层列表写入文件 #第一种要领,每一项用空格离隔,一个列表是一行写入文件 data =[ ['a','b','c'],['a','b','c'],['a','b','c']] with open("data.txt","w") as f: #设置文件对象 for i in data: #关于双层列表中的数据 i = str(i).strip('[').strip(']').replace(',','').replace('\'','')+'\n' #将个中每个列表范例化成字符串 f.write(i) #写入文件 #第二种要领,直接将每一项都写入文件 data =[ ['a','b','c'],['a','b','c'],['a','b','c']] with open("data.txt","w") as f: #设置文件对象 for i in data: #关于双层列表中的数据 f.writelines(i) #写入文件
更多Python相干技术文章,请接见Python教程栏目举行进修!
以上就是python怎样翻开一个txt文件的细致内容,更多请关注ki4网别的相干文章!