标签:
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC # ##默认读取模式 file = open("test_file","r",encoding="utf-8") #文件句柄 print(file.read()) data = file.read() #所有内容 data1 = file.read() #第二次读,是读不出数据的 file.seek(0) #将光标归零 data2 = file.read() #光标归零后就可以再出读出数据 file.close()
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC file = open("test_file","r",encoding="utf-8") #文件句柄 print(file.read()) #读出全部 file.seek(0) print(file.readline()) #读出一行 file.seek(0) print(file.readlines()) #把文章内容以换行符分割,并生成list格式 C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/file.py 1如果你真的爱我 让我走开 2心疼你当初反覆那样的说 3如果你真的爱我 让我走开 4我决心不从旧梦中 挣脱 5如果你真的爱我 让我走开 6心疼你为我藏住分离的苦 7如果我知道你是这样的难过 8会一个人走向寂寞 1如果你真的爱我 让我走开 [‘1如果你真的爱我 让我走开\n‘, ‘2心疼你当初反覆那样的说\n‘, ‘3如果你真的爱我 让我走开\n‘, ‘4我决心不从旧梦中 挣脱\n‘, ‘5如果你真的爱我 让我走开\n‘, ‘6心疼你为我藏住分离的苦\n‘, ‘7如果我知道你是这样的难过\n‘, ‘8会一个人走向寂寞‘]
file = open("test_file","r",encoding="utf-8") #文件句柄 for i in range(5): print(file.readline()) #读出前五行 file.close()
for line in file.readlines(): #转化为列表格式了 print(line.strip())
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC file = open("test_file","r",encoding="utf-8") #文件句柄 #将文件全部读入内存 for index,line in enumerate(file.readlines()): #读列表和下标 if index == 9: print("-----------------") continue print(line.strip()) ‘‘‘ #这个效率最高,for line in file,逐行读到内存 ‘‘‘ count = 0 for line in file: if count == 9: print("--------------------") count += 1 continue print(line) count += 1 ‘‘‘
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC ##默认读取模式 file = open("test_file","r",encoding="utf-8") #文件句柄 print(file.tell()) #打印光标当前的位置 print(file.readline()) print(file.readline()) print(file.readline()) print(file.tell()) file.seek(0) #移动归零 print(file.tell()) file.flush #刷新,从内存写到磁盘 file.close() C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/file.py 0 1如果你真的爱我 让我走开 2心疼你当初反覆那样的说 3如果你真的爱我 让我走开 110 0
文件修改
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC #修改思路:打开一个文件,从旧文件,读一行写一行,改一行,写一行 f = open("test_file","r",encoding="utf-8") f_new = open("test_file.bak","w",encoding="utf-8") for line in f: if "心疼" in line: line = line.replace("心疼","xinteng") print(line) f_new.write(line) f.close() f_new.close()
#with #python 一行不要超过80个字符,用换行\ with open("yesterday","r",encoding="utf-8") as f,open("yesterday2","r",encoding="utf-8") as f2: for line in f: print(line) for line2 in f2: print(line2)
标签:
原文地址:http://www.cnblogs.com/dcc001/p/5758017.html