python 文字檔案操作

2022-06-19 16:57:15 字數 3296 閱讀 1621

檔案操作三步走:開啟、讀寫、關閉。

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編碼格式的文字檔案中的內容全部複製到另乙個使用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()

文字檔案操作

1 文字檔案的寫入 建立檔案流 filestream filestream new filestream c myfile file.txt filemode.create 建立寫入器 streamwriter sw new streamwriter filestream 以流的方式寫入資料 sw....

文字檔案操作

文字檔案操作 編寫乙個程式demo.py,要求執行該程式後,生成demo new.py檔案,其中內容與demo.py一樣,只是在每一行的後面加上行號以 開始,並且所有行的 符號垂直對齊。filename demo.py with open filename,r as fp lines fp.read...

C 文字檔案操作

如何向現有檔案中新增文字 usingsystem usingsystem.io classtest 如何建立乙個新文字檔案並向其中寫入乙個字串。方法可提供類似的功能。usingsystem usingsystem.io publicclasstexttofile alreadyexists.file...