python 从文本文件打印时需要删除\n的帮助

zy1mlcev  于 2023-03-11  发布在  Python
关注(0)|答案(2)|浏览(181)

我有一个名为Accounts.txt的文本文件,它以纯文本形式存储用户名和密码,如下所示:

Username Password
Username2 Password2
Username3 Password3etc

我的代码是:

with open("Accounts.txt", "a+") as Accounts:
    Accounts.write("LoginName") #write password to Accounts.txt
    Accounts.write(" ")
    Accounts.write("Password") #write password to Accounts.txt
    Accounts.write("\n") #create new line
    Accounts.seek(0) #start reading from start of txt
    lines = str(Accounts.readlines())
    cleanedlines = lines.replace("\n","")
    print(cleanedlines, end = "")

运行此命令的输出如下所示:

C:\Users\drago\Desktop\PythonPractice\venv\Scripts\python.exe C:\Users\drago\Desktop\PythonPractice\FileAppendTest.py 
['mrwong poop123\n', 'edible_man weeeeed420\n', 'portarossa pigsanimalsgood\n', 'LoginName Password\n', 'LoginName Password\n', 'LoginName Password\n', 'LoginName Password\n', 'LoginName Password\n', 'LoginName Password\n']
Process finished with exit code 0

如何删除所有\n
我试过lines.replace("\n",""),它不工作。编辑:也使用strip和rstrip没有工作。我在pycharm上。

u7up0aaq

u7up0aaq1#

with open("C:\\Users\\jjnit\\Downloads\\test.txt", "a+") as Accounts:
    Accounts.write("LoginName") #write password to Accounts.txt
    Accounts.write(" ")
    Accounts.write("Password") #write password to Accounts.txt
    Accounts.write("\n") #create new line
    Accounts.seek(0) #start reading from start of txt
    lines = Accounts.readlines()
    new_lines = [lines[i].strip("\n") for i in range(len(lines))]
    print(new_lines, end = "")

您的问题是它只替换了第一个“\n”。这是因为您使用了lines = str(Accounts.readlines())。当您将其转换为字符串时,您将格式更改为:'[“a”,“B”,“c”,“d”,“a”]'。发生这种情况时,执行.replace[“b”]将仅替换第一个。由于重复的“\n”,因此仅替换了第一个,而所有其他内容保持不变。此外,当您执行.replace(“\n”,““),格式变为“[“a ' '",“b ' '",“c ''",“d ' '"]”无论如何,我希望这解决了您的问题。如果您将此应用于特定的内容,如果需要的话,我可以重新格式化代码以提高效率(尽管现在最容易理解)

h7appiyu

h7appiyu2#

你不想生成值列表的单个字符串表示,你想从列表的每个元素中删除换行符。

lines = Accounts.readlines())
cleanedlines = [x.rstrip('\n') for x in lines]
print(cleanedlines, end = "")

相关问题