“/n”在尝试写入新行时被写入文本文件

时间:2021-07-30 11:46:18

标签: python

我有一个 for 循环,我试图在其中将一些行写入文本文件。当我到达这一特定行时(然后我将其转换为字符串的数组)。我需要它来写入文件并在之后创建一个新行。

它正确地完成了所有这些,但是它也在后面以字符串形式添加了“\n”。这是我不想要的。这是我的所有代码:

    # this line opens a text file , stores the lines in an array and loads a line I am trying to alter into a variable
propinfo = open("D:\pythonProject\monop\propertyinfo.txt")
propinfolines = propinfo.readlines()
desiredline = (propinfolines[(players[playerturn].squareID) + 1])

# the lines below are an operation to split the line into an array by a comma , and change one part of that array
propkeyinfo = (desiredline.split(','))
propkeyinfo[14] = playerturn

# this line takes the array I just altered and puts in back into the array of lines in the correct position.
propinfolines[(players[playerturn].squareID) + 1] = str(propkeyinfo)
   

#i then reopen the file and write back each line from that array , when I get to the line I altered I create a new line after
propinfo = open("D:\pythonProject\monop\propertyinfo.txt", "w")
for i in range(41):
    if i == (players[playerturn].squareID) + 1:
            propinfo.write(propinfolines[i] + "\n")
        else:
                propinfo.write(propinfolines[i])
        propinfo.close()
<块引用>

['7', '4', '东方大道', '100', '50', '50', '6', '30', '90', '270', '400', '550', '326', '738', 1, '\n']

如何在不写“'\n'”的情况下创建这个新行

2 个答案:

答案 0 :(得分:1)

propinfo.readlines() 逐行读取文件,包括尾随的 '\n'。所以,如果你的线条看起来像

7,4,Oriental Avenue,100,50,50,6,30,90,270,400,550,326,738,1,

它会出来

'7,4,Oriental Avenue,100,50,50,6,30,90,270,400,550,326,738,1,\n'

这反过来将导致您在以逗号分隔后报告的列表,其中“\n”作为列表的最后一个元素。

如果将行 propkeyinfo = (desiredline.split(',')) 更改为

propkeyinfo = (desiredline.rstrip(',\n').split(','))

它去掉了尾随的 ',\n',所以结果列表不会有额外的元素。

但是,如果您需要该行与输入的格式相同 - 这在您写回原始文件时似乎很可能 - 而不是上面的,将 str(propkeyinfo) 替换为 {{1} } 重建逗号分隔的字符串并将其直接写入文件,无需任何额外的 '\n'。

答案 1 :(得分:0)

答案:你不能,如果你想在文件上写一个新行,你必须使用 propinfo.write(propinfolines[i] + "\n")