Skip to main content
 首页 » 编程设计

Python:无法从字符串中删除换行符

2025年05月04日21hnrainll

这有点奇怪,但就是这样。

下面是一些代码,可以将文件作为日志打开,并将一些控制台输出通过管道传输到其中。稍后我打开该文件并想将文件的内容(每一行是一个文件的目录路径)复制到我当前的目录中,但是我的 shell 返回一个错误,说它找不到该文件,因为它有一个换行符附加到它。当我在脚本中打印该行时,它没有换行符,但当我尝试在脚本中复制它时,它有,这是怎么回事?

with open("log.txt", 'a+') as log: 
    for something in something_else: 
        p1 = subprocess.Popen(["script.py", "-x", "-options"], stdout=subprocess.PIPE) 
        p2 = subprocess.Popen(["egrep", 'abc|xyz'], stdin=p1.stdout, stdout=log, universal_newlines=True) 
        p1.stdout.close() 
        output = p2.communicate()[0] #Debug purposes 

稍后...

with open("log.txt") as log2: 
    for line in log2: 
        line = re.sub(".pattern", "pattern", line) 
        line.rstrip() #doesn't work 
        call(['cp', line, '.']) 

我的 shell 返回:cp cannot stat `path/to/dir**\n**' no such file or directory

请您参考如下方法:

字符串在 Python 中是不可变的,请改用 line = line.rstrip()。