python - 使用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']
解决方案
推荐阅读
- material-design-in-xaml - 继承的控件不继承 Material Design 风格
- angular - 在其他组件Angular中使用组件方法
- python - 显示 jinja 中字典列表中的所有值
- r - 用于计算张量积的 R 向量内存已耗尽
- node.js - 如何使用 Fetch() 和 Node.js 评估来自服务器的 API 响应并在客户端采取相应的行动
- nginx - 用于服务的 Cronjob
- python - 我可以在这里信任用户输入吗?
- javascript - 在自己的域上显示远程网站内容的正确方法
- python - 最低平台
- solidity - 访问嵌套映射solidity