App下載

python文件流讀寫怎么操作?

詩與彼方 2021-08-09 16:42:32 瀏覽數 (3169)
反饋

python文件流操作一般也就是讀和寫兩個操作,雖然看著簡單,但實際上操作還是比較復雜的,接下來這篇文章我們就來探討一下python文件流讀寫操作吧。

文件流的讀寫

讀取保存數據為數組的txt文件

使用try進行異常發(fā)現,使用while檢測文件末尾進行讀取

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遍歷讀取的每一行,進行一次性的讀取和輸入

下面調用的程序讀取的數據是

程序讀取的數據

result = list()
    with open('../test/parameter.txt') as  f:
        for line in f.readlines():
            temp = list()
            # 逐個遍歷對應每一行元素,將之轉為對應的數據
            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中的結果是",result)

刪除str中的特定字符

刪除字符串首尾的多余字符串strip()

# 刪除字符串中多余字符
def string_remove():
   str1 = ' abc     
'
   print str1.strip()   # abc

   str2 = '----abcdf++++'
   print str2.strip('-+')  # abcdf

replace函數,刪除字符串中某一個所有的字符串

ss = 'old old string'
ret = ss.replace('old', 'new', 1)
print(ret)

sub函數,同時刪除多個字符串,這里使用了正則表達式

str2 = '
abc
wrt22	666	'  # 刪除字符串中的所有
,	
import re
print(re.sub('[
	]','',str2))   # abcwrt22666

以上就是python文件流讀寫的詳細內容,更多python的學習資料請關注W3Cschool其它相關文章!


0 人點贊