Python 如何删除此行中的\n?

Python 如何删除此行中的\n?,python,Python,我的程序有一部分可以从.txt文件中读取行。每行都是一个计算机名。它将computername作为变量输入到目录名中。我得到一个错误,上面写着 没有这样的文件或目录://COMPUTERNAME\n/c$/test 如何删除\n,以便创建//COMPUTERNAME/c$/test的目录名 以下是我的代码中有问题的部分: import os import shutil import fileinput import re # used to replace string import sys

我的程序有一部分可以从
.txt
文件中读取行。每行都是一个计算机名。它将computername作为变量输入到目录名中。我得到一个错误,上面写着

没有这样的文件或目录:
//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())
你可以试试

copyfiles(servername.strip())
这应该可以去掉空格和新行

你可以试试

copyfiles(servername.strip())

它应该去掉空格和新行

以删除空白字符,其中包括新行字符
\n
您可以使用
strip()
,因此最后两行变成:

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

要删除包括换行符
\n
在内的空白字符,可以使用
strip()
,使最后两行变为:

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

您不需要
re
。只需使用常规的
str.replace()
函数:
servername=servername.replace('\n')
copyfiles(servername.replace('\n'))
.Hm,我想你会的?我做了,但我在strip()上没有任何运气。Christian,别理re。我正在将其用于代码中的另一个函数。您不需要
re
。只需使用常规的
str.replace()
函数:
servername=servername.replace('\n')
copyfiles(servername.replace('\n'))
.Hm,我想你会的?我做了,但我在strip()上没有任何运气。Christian,别理re。我把它用于代码中的另一个函数。很好。我没有想到OP必须删除其他空白字符。使用
strip()。我没有想到OP必须删除其他空白字符。使用
strip()?