首页 > 解决方案 > 使用python将列表写入.txt文件时,出现'\n'(反斜杠n)?

问题描述

我的脚本的结果不符合预期。我希望能够在 .txt 的每一行中写一个单词,然后将它们读入我的脚本中添加一些内容,然后将它们输出到 PowerShell 脚本。

我没想到的第一件事是 \n 我认为它来自 .txt 中的换行。删除它的最佳方法是什么?

第二件事是第一个和最后一个 [ ] ,这并不令人惊讶,但我仍然不知道如何将其过滤掉。最好的方法是什么?

我是python/编码方面的新手和自我思考,如果代码有点混乱,我深表歉意。

这是我的代码:

txt_list = []
new_txt_list = []
def StringDeleter(read_path):
    with open(read_path, 'r') as read_txt:
        for line in read_txt:
            line = str(line)
            txt_list.append(line)
    for input in txt_list:
        input1 = "-" + input
        input2 = "." + input
        input3 = "-[" + input + "]"
        input4 = ".[" + input + "]"
        input5 = "[" + input + "]"
        input6 = input
        new_txt_list.append(input1)
        new_txt_list.append(input2)
        new_txt_list.append(input3)
        new_txt_list.append(input4)
        new_txt_list.append(input5)
        new_txt_list.append(input6)
StringDeleter(r"C:\Users\user\Desktop\123.txt")
with open(r"C:\Users\user\Desktop\Temp.PowerShell.ps1", "w") as temp_ps_script:
    temp_ps_script.write(str(new_txt_list))

这是输入文件“123.txt”:

String1
String2

这是输出文件“Temp.PowerShell.ps1”:

['-String1\n', '.String1\n', '-[String1\n]', '.[String1\n]', '[String1\n]', 'String1\n', '-String2', '.String2', '-[String2]', '.[String2]', '[String2]', 'String2']

标签: python

解决方案


如果它们位于字符串的末尾或开头,您可以使用strip(),但如果您只想从字符串中删除所有 \n,请尝试此操作。

line = line.replace('\n','')

代替()


推荐阅读