如何删除此行中的\ n?

时间:2017-05-30 17:46:21

标签: python

我的程序中有一部分从.txt文件中读取行。每一行都是一个计算机名。它将计算机名称作为变量并将其输入到目录名称中。我收到一条错误

没有此类文件或目录://COMPUTERNAME\n/c$/test

如何删除\n,以便创建目录名//COMPUTERNAME/c$/test

以下是我遇到问题的部分代码:

import os
import shutil
import fileinput
import re  # used to replace string
import sys # prevents extra lines being inputed in config
           # example: sys.stdout.write

def copyfiles(servername):
    # copy config to remote server
    source = os.listdir("C:/Users/name/Desktop/PythonUpdate") # directory where original configs are located
    destination = '//' + servername + '/c$/test/' # destination server directory
    for files in source:
        if files.endswith(".config"):
            shutil.copy(files,destination)

os.system('cls' if os.name == 'nt' else 'clear')
f = open("C:/Users/jm09580/Desktop/PythonUpdateOasis/serverlist.txt", "r")
for servername in f:
    copyfiles(servername)

更新 这有效:

array = []
with open("C:/Users/myuser/Desktop/PythonUpdate/serverlist.txt", "r") as f:
for servername in f:
    copyfiles(servername.strip())

2 个答案:

答案 0 :(得分:4)

要删除包含换行符\n的空格字符,您可以使用strip(),这样您的最后两行就会变为:

for servername in f:
    copyfiles(servername.strip())

答案 1 :(得分:1)

你可以尝试

copyfiles(servername.strip())

哪个应该摆脱空格和换行