python 文本文件操作


文件操作三步走:打開、讀寫、關閉。 

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file參數指定了被打開的文件名稱。

mode參數指定了打開文件后的處理方式。

encoding參數指定對文本進行編碼和解碼的方式,只適用於文本模式,可以使用Python支持的任何格式,如GBK、utf8、CP936等等。

文件打開模式

 

 

例:向文本文件中寫入內容,然后再讀出

s = 'Hello world\n文本文件的讀取方法、文本文件的寫入方法\n'
with open('sample.txt','w') as fp:      #默認使用cp936編碼
    fp.write(s*5)
#生成的文件放在.py文件所在文件夾

with open('sample.txt') as fp:
    print(fp.read())

E:\pytho_pycharm\venv\Scripts\python.exe E:/pytho_pycharm/prac.py
Hello world
文本文件的讀取方法、文本文件的寫入方法
Hello world
文本文件的讀取方法、文本文件的寫入方法
Hello world
文本文件的讀取方法、文本文件的寫入方法
Hello world
文本文件的讀取方法、文本文件的寫入方法
Hello world
文本文件的讀取方法、文本文件的寫入方法


Process finished with exit code 0

 

例:將一個CP936編碼格式的文本文件中的內容全部復制到另一個使用UTF8編碼的文本文件中。

#將一個CP936編碼格式的文本文件中的內容全部復制到另一個使用UTF-8編碼的文本文件中
def filecopy(srcc,dstt,srccEncoding,dsttEncoding):
    with open(srcc,'r',encoding=srccEncoding) as srcfp:
        with open(dstt,'w',encoding=dsttEncoding) as dstfp:
            dstfp.write(srcfp.read())

filecopy('sample.txt','sample_new.txt','cp936','utf8')

#讀取這兩個文件
with open('sample.txt') as fp: #默認為CP936編碼
    print(fp.read())
print()
with open('sample_new.txt',encoding='utf-8') as fp: #如果是其他編碼需要有(encoding = )
    print(fp.read())

  

例:遍歷並輸出文本文件的所有行內容

with open('sample.txt') as fp:
    for line in fp:
        print(line,end='')

  

 案例:

根據考試成績,統計學科等級水平。 分析:某中學對學生的附加科目進行能力測試,並按以下標准統計學科等級水平。

(1)生物和科學兩門課都達到60分,總分達到180分為及格;

(2)每門課達到85分,總分達到260分為優秀;

(3)總分不到180分或有任意一門課不到60分,為不及格。

學生成績原始數據如圖所示。

編程要求:從score.txt文件中讀取學生成績數據,判定等級並寫入level.txt文件中。

L = list(open('score.txt')) #文件中的每一行都是列表的一個元素
f = open('level.txt','w')   #新建level文件夾寫入
flag = 1

for s in L:
    x = s.split()
    if flag:
        flag = 0
        f.write("%s\t%s\t%s\t%s\t是否及格\n" % (x[0], x[1], x[2], x[3]))
        continue
    for i in range(len(x)): #假如一行有多個類別就要用for循環
        x[i] = int(x[i])
    sum = x[1]+x[2]+x[3]
    if x[1]>=85 and x[2]>=85 and x[3]>=85 and sum>=260 :
        key = '優秀'
    elif x[2]>=60 and x[3]>=60 and sum>=180:
        key = '及格'
    elif x[1]<60 or x[2]<60 or x[3]<60 or sum<180 :
        key = '不及格'
    f.write('%d\t%d\t%d\t%d\t%s\n'%(x[0],x[1],x[2],x[3],key))
f.close()
f = open('level.txt')
print(f.read())

  

s=open('score.txt')
f=open('level.txt','w')
x = s.readline().split()
f.write()
while True:
    x=s.readline().split()
    if len(x)==0:
        break
    for i in range(1,len(x)):
        x[i]=int(x[i])
    sum=x[1]+x[2]+x[3]
    if x[1]>=85 and x[2]>=85 and x[3]>=85 and sum>=260:
        key = "優秀"
    elif x[2]>=60 and x[3]>=60 and sum>=180:
        key = "及格"
    else:
        key = "不及格"
    f.write()
s.close()
f.close()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM