2015-11-02 66 views
0

我有一個文本文件IDlistfix,其中包含一個youtube視頻ID列表。我正在嘗試製作一個新的文本文件,newlist.txt,這是第一個帶有撇號的視頻中的ID以及ID之間的逗號。這是我寫來實現:找不到功能出錯的地方

n = open('IDlistfix','r+') 
j = open('newlist.txt','w') 
line = n.readline() 

def listify(rd): 
    return '\'' + rd + '\',' 

for line in n: 
    j.write(listify(line)) 

這讓我的','rUfg2SLliTQ的輸出,我所期待的輸出爲'rUfg2SLliTQ',。我的功能在哪裏出錯?

+0

嘗試'rd.strip()'' – postelrich

+0

rd.strip()'將擺脫換行符。 – Zizouz212

回答

1

你一定要剝去它的換行:

j.write(listify(line.strip())) # Notice the call of the .strip() method on the String 
1

嘗試刪除結尾的空白,並返回一個格式化字符串:

n = open('IDlistfix','r+') 
j = open('newlist.txt','w') 
line = n.readline() 

def listify(rd): 
    # remove trailing whitespace 
    rd = rd.rstrip() 
    # return a formatted string 
    # this is generally preferable to '+' 
    return "'{0}',".format(rd) 

for line in n: 
    j.write(listify(line)) 
1

的問題必須是,

`return '\'' + rd + '\`',' 

,因爲RD爲經 '/ N' 結尾。 從rd中刪除'/ n',它應該沒問題

1

是行更改問題。

變化:

for line in n: 
     j.write(listify(line.replace('\n','')))