簡體   English   中英

open()不起作用后關閉文件

[英]Close file after open() doesn't work

當我運行此函數時,它掛起,因為我正在使用open()函數讀取csv,並且需要將其關閉。 我把close()函數放到了我認為應該去的地方,但是似乎沒有用。 我已經將close()函數與“ while True”縮進符,“ for i in byte”縮進符放在一起,並且對任何一個都不起作用。 我究竟做錯了什么?

def parse(text):
    #states
    is_token = False
    previous_character_is_escape = False
    no_quote_value = True
    quote_value = False


    file_base = os.path.basename('"app/csv_upload_directory/%s' % text)
    new_base = os.path.splitext(file_base)[0]

    row_counter = 1
    token_counter = 0
    fo = open("csv_upload_directory/%s_results.csv" % new_base, "w+")

    fo.write("Row %i" % row_counter + '\n')
    row_counter += 1
    with io.open(text,'rb',newline=None) as f:
        while True:
            byte = f.read(1)
            for i in byte:
                #print "%s,%s" % (no_quote_value,previous_character_is_escape)
                if is_token == False:
                    if i == '"':
                        fo.write(i)
                        token_counter = 0
                        is_token = True
                        no_quote_value = False
                        quote_value = True
                    elif i == '\n':
                        fo.write(",")
                        fo.write("%i" % token_counter)
                        fo.write('\n')
                        fo.write("Row %i" % (row_counter))
                        fo.write("\n")
                        token_counter = 0
                        row_counter += 1
                    elif i == ',':
                        fo.write(",")
                        fo.write("%i" % token_counter)
                        fo.write('\n')
                        token_counter = 0
                    elif no_quote_value == True:
                        fo.write(i)
                        token_counter += 1
                        is_token = True
                        quote_value = False
                    else:
                        fo.write(i)
                        token_counter += 1


                elif is_token == True:
                    # start of an escape sequence
                    if i == '\\':
                        fo.write(i)
                        token_counter += 1
                        previous_character_is_escape = True
                    # for line delimiter, the quoted values are being processed outside token
                    elif no_quote_value == True and i == '\n':
                        fo.write(",")
                        fo.write("%i" % token_counter)
                        fo.write('\n')
                        fo.write("Row %i" % (row_counter))
                        fo.write("\n")
                        token_counter = 0
                        row_counter += 1
                        is_token = False
                    # if token is not a quoted value but ends with quotes, and there is no escape character
                    elif no_quote_value == True and previous_character_is_escape == False and i == '"':
                        fo.write(i)
                        fo.write("This is a not a valid token, this is not a quoted value but there is an ending quote")
                        return False
                    # builds off previous_character_is_escape and captures any escape sequence
                    elif previous_character_is_escape == True:
                        fo.write(i)
                        token_counter += 1
                        previous_character_is_escape = False
                    # this type of quote is the end of token, returns back to other if statement
                    elif previous_character_is_escape == False and i == '"':
                        fo.write(i)
                        no_quote_value = True
                        quote_value = False
                        is_token = False
                    # if token starts as a quote but ends without quotes
                    elif quote_value == True and previous_character_is_escape == False and i == ',':
                        fo.write(i)
                        fo.write("This is not a valid token, there should be a quote at the end of this token")
                        return False
                    # this comma marks the end of a non quoted token, this invokes a newline
                    elif no_quote_value == True and previous_character_is_escape == False and i == ',':
                        fo.write(",")
                        fo.write("%i" % token_counter)
                        fo.write('\n')
                        token_counter = 0
                        is_token = False
                    elif no_quote_value == False and i == ',':
                        fo.write(i)
                        fo.write("DONG")
                    else:
                        fo.write(i)
                        token_counter += 1
        fo.close()

parse('example.csv')

從您的評論看來,關閉文件實際上不是您的問題(盡管這是您應該注意的問題)。 真正的問題是您的功能永無止境。

這是因為您將永遠循環,嘗試每次迭代讀取一個字符。 讀取完所有文件后,您不會注意到它從f.read(1)獲得空字節f.read(1) 您應該添加一些邏輯以在發生這種情況時跳出循環。

另一個問題:您當前正在使用for循環遍歷從read(1)獲得的一字節字符串。 不需要該循環,這使得使用break語句很難打破while循環。

嘗試:

with io.open(text,'rb',newline=None) as f, fo:   # add fo to the with statement
    while True:
        i = f.read(1)        # read directly to "i", no need for the extra loop on bytes
        if i == '':          # check if read gave us an empty string (happens at EOF)
            break
        if is_token == True:
            # ...

因此,您將在此處打開兩個文件。 一個以fo為參考,另一個以f為參考。

對於fo ,您正在使用open()方法執行文件操作,您需要使用fo.close()將其適當關閉。

但是, f並非如此。 由於您使用的with ... open()方法,因此不需要關閉它,因為它可以在完成代碼塊執行后有效地處理關閉文件。 在此處閱讀相關文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM