f = open('a.txt',encoding='utf-8') content = f.read() #<class 'str'> print(content,type(content)) #释放资源 f.close() #释放后调用资源 #content1 = f.read() #print(content1) # ValueError: I/O operation on closed file.
with open('a.txt',encoding = 'utf-8') as f: content3 = f.read() print(content3)
with open('a.txt',encoding = 'utf-8') as f: content4 = f.read(30) print(content4)
- 注意:因为Windows支持GBK编码格式,而python支持utf-8格式,所有想要写入中文,就得设置一下编码 encoding = 'utf-8'
with open('aa.txt','a',encoding = 'utf-8') as f: f.write('we can english!') f.write('我能不能是中文呢?')
追加操作:在open()内部写入 "a" 即append 即可
with open('aa.txt','a',encoding = 'utf-8') as f: # \r\n 是换行操作 f.write('\r\nhahaha') f.write('我和哈哈是追加的。')
文件为:
name,sex,age,address,email 小花,女,19,安徽合肥,1001@163.com 小虎,男,21,江苏南京,1002@163.com 小倩,女,22,湖北武汉,1003@163.com 小壮,男,23,云南昆明,1004@163.com 小小,女,34,山东临沂,1005@163.com
with open('c.txt','r',encoding = 'utf-8') as f: #list1 = f.readline() # <class 'str'> 当读取一行或者直接read(),格式是字符串 list2 = f.readlines() # 此时读取的是列表格式,可以进行操作 # 以逗号进行分割,然后遍历获取第列数据 for line in list2: list3 = line.split(',') print(list3[0],type(list3)) #name <class 'list'>
list4 = [['1', 'q', 'w', 'e', 'r', 't','y'],['2','qq','ww','ee','rr','tt','yy'],['3','qqq','www','eee','rrr','ttt','yyy']] with open('f.txt','w') as f4: for i in list4: print(i,type(i)) i = '|'.join(i) i = i +'\r\n' f4.write(i) f4.close()