1. 程式人生 > 其它 >python基礎複習--讀文字檔案(19)

python基礎複習--讀文字檔案(19)

技術標籤:python

#讀文字檔案   read(n)讀n個字元  read()讀整個文字    n>實際個數,讀取實際個數    如果已經讀到檔案尾部了,再度返回空串
#遇到\n  \r    \r\n作為換行標識,並統一轉換為\n作為文字輸入換行符
def writeFile():
    fobj=open("./student.txt","wt")
    fobj.write("abc\nxyz")
    fobj.close()
def readFile():
    fobj=open("./student.txt"
,"rt") s=fobj.read() print(s) fobj.close() try: writeFile() readFile() except Exception as err: print(err) def writeFile(): fobj=open("./student.txt","wt") fobj.write("abc\nxyz") fobj.close() def readFile(n): fobj=open(
"./student.txt","rt") s=fobj.read(n) print(s) print(len(s)) fobj.close() try: writeFile() n=520 readFile(n) except Exception as err: print(err) #如果檔案指標已經到了檔案的尾部,再讀就返回一個空串 def writeFile(): fobj=open("./student.txt","wt") fobj.
write("ab c\nxyz") fobj.close() def readFile(): fobj=open("./student.txt","rt") flag=1 st="" while flag==1: s=fobj.read(1) if s!="": st=st+s else: flag=0 fobj.close() print(st) try: writeFile() readFile() except Exception as err: print(err) #讀取一行的函式readline #readline()一直讀到'\n'或檔案尾為止 #如果讀到'\n',那麼返回的字元包含'\n' #如果到了檔案尾部,再次就讀到一個空字串 def writeFile(): fobj=open("./student.txt","wt") fobj.write("abc\nxyz") fobj.close() def readFile(): fobj=open("./student.txt","rt") s=fobj.readline() print(s,"length=",len(s)) s=fobj.readline() print(s,"length=",len(s)) s=fobj.readline() print(s,"length=",len(s)) fobj.close() try: writeFile() readFile() except Exception as err: print(err) #一行一行讀取檔案資料 def writeFile(): fobj=open("./abc.txt","wt") fobj.write("abc\nxyz") fobj.close() def readFile(): fobj=open("./abc.txt","rt") goon=1 st="" while goon==1: s=fobj.readline() if s!="": st=st+s else: goon=0 fobj.close() print(st) try: writeFile() readFile() except Exception as err: print(err) #讀取所有行的函式readlines一般和for配合使用 def writeFile(): fobj=open("./abc.txt","wt") fobj.write("abc\neee\nxyz") fobj.close() def readFile(): fobj=open("./abc.txt","rt") # print(fobj.readlines())#['abc\n', 'eee\n', 'xyz'] for x in fobj.readlines(): print(x,end='') fobj.close() try: writeFile() readFile() except Exception as err: print(err) #讀取儲存在student.txt檔案學生資訊 class student: def __init__(self,name,gender,age):#建構函式 self.name=name self.gender=gender self.age=age def show(self):#類函式 print(self.name,self.gender,self.age) students=[] try: f=open("student.txt","rt") while True: name=f.readline().strip("\n")#將一行的前後/n字元去掉 if name=="": break gender=f.readline().strip("\n") age=float(f.readline().strip("\n")) students.append(student(name,gender,age))#類放入students f.close() for s in students: s.show() except Exception as err: print(err)