簡體   English   中英

為什么在python中寫入文件不起作用?

[英]Why doesn't this writing to file in python work?

以下代碼背后的想法是,如果變量crop已經包含在.txt文件中,則變量quantity將被添加到與crop相同的行的末尾。 這是我嘗試這樣做,但它不起作用:你真的需要運行它來理解,但實質上,列表的錯誤部分被添加到,一個不斷擴展的系列'/'出現和行打破消失。 有誰知道如何修改此代碼,使其正常運行?

應該輸出什么:

Lettuce 77 88 100
Tomato 99

實際輸出的是什么:

["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "]

碼:

def appendA ():

 with open('alpha.txt', 'r') as file_1:
  lines = file_1.readlines()

  for line in lines:
    if crop in line:
        index = lines.index(line)
        line = str(line + quantity + ' ')
        lines [index] = line
        newlines = str(lines)

        #The idea here is that the variable quantity is added onto the end
        # of the same row as the entered crop in the .txt file.


        with open('alpha.txt', 'w') as file_3:
            file_3.write (newlines)

def appendB ():

 with open('alpha.txt', 'a') as file_2:

    file_2.write ('\n')
    file_2.write (crop + ' ')
    file_2.write (quantity + ' ')

crop = input("Which crop? ")
quantity = input("How many? ")

with open('alpha.txt', 'a') as file_0:

 if crop in open('alpha.txt').read():
    appendA ()
 else:
    appendB ()
newlines = str(lines) # you convert all lines list to str - so you get default conversion

如果你想在中間寫,你也應該替換整個文件

你也可以閱讀appendB,因為你仍然檢查每一行,你的代碼無論如何都不是最佳的性能:)

from os import remove, close

def appendA(filename, crop, quantity):

    result = []
    exists = False
    with open(filename, 'r') as file_1:
        lines = file_1.readlines()

    for line in lines:
        if not crop in line:
            result.append(line)
        else:
            exists = True
            result.append(line.strip('\n') + quantity + '\n')


    if not exists:          
        with open(filename, 'a') as file_2:
            file_2.write ('\n' + crop + ' ' + quantity + ' ')
    else:
        tmp_file = filename + '.tmp'
        with open(tmp_file, 'w') as file_3:
            file_3.write(result)
            remove(filename)
            move(tmp_file, filename)

開始吧! 您的代碼應如下所示:

def appendA():
    with open('alpha.txt', 'r') as file_1:
        lines = []

        for line in file_1:
            if crop in line:
                line = str(line.rstrip("\n") + quantity + "\n")
            lines.append(line)

        #The idea here is that the variable quantity is added onto the end
        # of the same row as the entered crop in the .txt file.
        with open('alpha.txt', 'w') as file_3:
            file_3.writelines(lines)


def appendB():
    with open('alpha.txt', 'a') as file_2:
        file_2.write('\n')
        file_2.write(crop + ' ')
        file_2.write(quantity + ' ')

crop = "Whichcrop"
quantity = "+!!!+"

with open('alpha.txt') as file_0:
    if crop in file_0.read():
        print("appendA")
        appendA()
    else:
        print("appendB")
        appendB()


 with open('alpha.txt', 'a') as file_0:
     if crop in open('alpha.txt').read():
         appendA ()
     else:
         appendB ()

你也犯了幾個錯誤。 這行“以open('alpha.txt','a')作為file_0:”打開文件,上下文附加到文件末尾,但你不使用變量file_0。 我認為這是額外的。 在下一步中,您打開文件以檢查“在打開時裁剪('alpha.txt')。read()”,但從不關閉它。

[“['\\ n','生菜77 \\ n88','番茄88'] 100”]你得到這樣一個輸出,因為你使用write而不是writelines:with open('alpha.txt','w') as file_3:file_3.write(newlines)

你也可以在每次迭代后寫入文件,更好地形成字符串列表然后寫入文件。

  1. “str(lines)”:lines是列表類型,你可以使用'.join(lines)將它轉換為字符串。
  2. “行中的行”:“行”以“\\ n”結尾
  3. 代碼縮進錯誤:“line newlines =''。join(lines)”和后面的內容
  4. “如果在線上裁剪”是錯誤的,如果裁剪名為“AA”和“AABB”,新輸入“AA”返回true,則數量將附加到包括“AA”在內的所有行,而不僅僅是“AA”行。


    def appendA():
        with open('alpha.txt', 'r') as file_1:
            lines = file_1.readlines()

            for line in lines:
                if crop in line:
                    index = lines.index(line)
                    line = str(line.replace("\n", "") + ' ' + quantity + '\n')
                    lines[index] = line
            newlines = ''.join(lines)

            # The idea here is that the variable quantity is added onto the end
            # of the same row as the entered crop in the .txt file.
            with open('alpha.txt', 'w') as file_3:
                file_3.write(newlines)


    def appendB():
        with open('alpha.txt', 'a') as file_2:
            file_2.write("\n")
            file_2.write(crop + ' ')
            file_2.write(quantity + ' ')


    crop = input("Which crop? ")
    quantity = input("How many? ")

    with open('alpha.txt', 'a') as file_0:
        if crop in open('alpha.txt').read():
            appendA()
        else:
            appendB()


暫無
暫無

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

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