您好,登錄后才能下訂單哦!
這篇文章主要講解了“python文件流讀寫如何操作”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“python文件流讀寫如何操作”吧!
使用try進(jìn)行異常發(fā)現(xiàn),使用while檢測(cè)文件末尾進(jìn)行讀取
file_to_read = raw_input("Enter file name of tests (empty string to end program):") try: infile = open(file_to_read, 'r') while file_to_read != " ": file_to_write = raw_input("Enter output file name (.csv will be appended to it):") file_to_write = file_to_write + ".csv" outfile = open(file_to_write, "w") readings = (infile.readline()) print readings while readings != 0: global count readings = int(readings) minimum = (infile.readline()) maximum = (infile.readline())
使用for遍歷讀取的每一行,進(jìn)行一次性的讀取和輸入
下面調(diào)用的程序讀取的數(shù)據(jù)是
result = list() with open('../test/parameter.txt') as f: for line in f.readlines(): temp = list() # 逐個(gè)遍歷對(duì)應(yīng)每一行元素,將之轉(zhuǎn)為對(duì)應(yīng)的數(shù)據(jù) b = line.strip(",][").split(',') if(len(b) >= 5): b.pop() for a in b: a = a.replace('[','').replace(']','') temp.append(float(a)) result.append(temp) #print("中途打印的temp是",temp) #print("加入到result中的結(jié)果是",result)
刪除字符串首尾的多余字符串strip()
# 刪除字符串中多余字符 def string_remove(): str1 = ' abc ' print str1.strip() # abc str2 = '----abcdf++++' print str2.strip('-+') # abcdf
replace函數(shù),刪除字符串中某一個(gè)所有的字符串
ss = 'old old string' ret = ss.replace('old', 'new', 1) print(ret)
sub函數(shù),同時(shí)刪除多個(gè)字符串,這里使用了正則表達(dá)式
str2 = ' abc wrt22 666 ' # 刪除字符串中的所有 , import re print(re.sub('[ ]','',str2)) # abcwrt22666
感謝各位的閱讀,以上就是“python文件流讀寫如何操作”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)python文件流讀寫如何操作這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。