簡體   English   中英

Python:無法從str中刪除換行符

[英]Python: Unable to remove newline from str

這有點不可思議,可是在這里。

下面是一些代碼,這些文件打開一個文件作為日志,並將某些控制台輸出通過管道傳送到該文件中。 稍后,我打開該文件,並想將文件的內容(每行是文件的目錄路徑)復制到當前目錄中,但是我的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無法統計`path / to / dir ** \\ n **'沒有這樣的文件或目錄

字符串在Python中是不可變的,請改用line = line.rstrip()

這是因為line.rstrip()返回原始字符串的副本(請參閱docs )。

因此,諸如line = line.rstrip()之類的工作即可完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM