简体   繁体   English

为什么在python中写入文件不起作用?

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

The idea behind the following code is that the if the variable crop is already contained within the .txt file the variable quantity will be added on to the end of the same line as crop . 以下代码背后的想法是,如果变量crop已经包含在.txt文件中,则变量quantity将被添加到与crop相同的行的末尾。 This is my attempt at doing this, however it doesn't work: you really need to run it to understand, but, essentially, the wrong section of the list is added to, an ever expanding series of '/' appear and the line breaks disappear. 这是我尝试这样做,但它不起作用:你真的需要运行它来理解,但实质上,列表的错误部分被添加到,一个不断扩展的系列'/'出现和行打破消失。 Does anyone know how to modify this code so it functions properly? 有谁知道如何修改此代码,使其正常运行?

What should be outputted: 应该输出什么:

Lettuce 77 88 100
Tomato 99

What actually is outputted: 实际输出的是什么:

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

Code: 码:

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

and also you should replace whole file if you want to write in the middle 如果你想在中间写,你也应该替换整个文件

And you can also get read of appendB, because you still check every line and your code anyway is not optimal in terms of performance :) 你也可以阅读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)

Let's start! 开始吧! Your code should look something like this: 您的代码应如下所示:

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 ()

Also you make several mistakes. 你也犯了几个错误。 This line "with open('alpha.txt', 'a') as file_0:" open file with context for append in the end of file, but you dont use variable file_0. 这行“以open('alpha.txt','a')作为file_0:”打开文件,上下文附加到文件末尾,但你不使用变量file_0。 I think it's extra. 我认为这是额外的。 On next step you opened file for check "crop in open('alpha.txt').read()", but never close it. 在下一步中,您打开文件以检查“在打开时裁剪('alpha.txt')。read()”,但从不关闭它。

["['\\n', 'Lettuce 77 \\n88 ', 'Tomato 88 ']100 "] You get such a output because, you use write instead of writelines: with open('alpha.txt', 'w') as file_3: file_3.write (newlines) [“['\\ n','生菜77 \\ n88','番茄88'] 100”]你得到这样一个输出,因为你使用write而不是writelines:with open('alpha.txt','w') as file_3:file_3.write(newlines)

Also you write in the file after each iteration, better to form a list of strings and then write to file. 你也可以在每次迭代后写入文件,更好地形成字符串列表然后写入文件。

  1. "str(lines)": lines is list type, you can use ''.join(lines) to convert it to a string. “str(lines)”:lines是列表类型,你可以使用'.join(lines)将它转换为字符串。
  2. "line in lines": "line" end with a "\\n" “行中的行”:“行”以“\\ n”结尾
  3. Code indent error: "line newlines = ''.join(lines)" and the follow 代码缩进错误:“line newlines =''。join(lines)”和后面的内容
  4. "if crop in lines" is mistake, if crop named "AA" and "AABB", the new input "AA" with return true, the quantity will be appended to all lines including "AA" ,not only the "AA" line. “如果在线上裁剪”是错误的,如果裁剪名为“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