2017-03-16 101 views
0

我試圖將列表的內容寫入文本文件,列表中的每個項目在新行上都沒有任何空行。我的問題似乎是從通過循環多個csv文件並將它們合併到一個列表中獲取的項目創建大型列表的工件。也許我只是需要結合不同的列表來修復單個單詞之後的「\ n」,而不是列表之間......?避免將空白空間寫入文本列表到文本文件

some_list = [] # list of csv files 
for i in os.listdir('filepath_to_directory_with_csv_files'): 
    some_list.append(i) 
print (some_list) 

[ 'A_test.csv', 'B_test.csv']

CombinedList = [] # list containing all the rows in each csv file 
for InFileName in some_list: # for loop to capture data from all csv files 
    InFile = open(InFileName, 'r') 
    PathwayList.append(InFile.readlines()) 
    InFile.close() 

print (CombinedList) 

[[ '這\ n', '爲\ n', 'A \ n', '測試' ],[ '這\ n', '爲\ n', 'B \ n', '測試']]

New_list = [item for sublist in CombinedList for item in sublist] 
print (New_list) 

[ '這\ n', '爲\ n',「A \ n ','test','This \ n','是\ n','B \ n','test']

with open("CombinedList.txt", "w") as f: 

    for line in New_list: 
     f.write(line + "\n") 
    print('File Successfully written.') 

文件成功寫入。

+0

那麼問題是什麼? –

回答

0

爲避免出現雙行換行符,您可以首先從文件中讀取每一行中的任意'\ n',然後向全部添加'\ n'。

PathwayList.append([line.rstrip('\n')+'\n' for line in InFile]) 

輸出:[['This\n', 'is\n', 'A\n', 'test\n'], ['This \n', 'is\n', 'B\n', 'test\n']]

+1

注意:您需要從'f.write'調用中刪除'+'\ n「',或者您只需可靠地雙行換行。 :-) – ShadowRanger

0

什麼你可能(只是猜測,因爲你在沒有100%明確制定問題)要的是:

CombinedList = [['This\n', 'is\n', 'A\n', 'test'], ['This \n', 'is\n', 'B\n', 'test']] 
# New_list = ['This\n', 'is\n', 'A\n', 'test', 'This \n', 'is\n', 'B\n', 'test'] 
for item in CombinedList: 
    line = '' 
    for word in item: 
     line += word.replace('\n', ' ') 
    f.write(line + "\n") 
    # print(line) 

此寫入(打印):

This is A test 
This is B test