【问题标题】:Avoid empty space writing list to text file避免空白将列表写入文本文件
【发布时间】:2017-03-16 01:01:36
【问题描述】:

我正在尝试将列表的内容写入一个文本文件,其中列表中的每个项目都在一个新行上,中间没有任何空行。我的问题似乎是从循环多个 c​​sv 文件中抓取的项目创建一个大列表并将它们组合成一个列表的工件。也许我只需要以不同的方式组合列表来修复单个单词之后的“\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)

[['This\n', 'is\n', 'A\n', 'test'], ['This\n', 'is\n', 'B\n', 'test' ]]

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

['This\n', 'is\n', 'A\n', 'test', 'This\n', 'is\n', 'B\n', 'test']

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

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

文件已成功写入。

【问题讨论】:

  • 那么问题出在哪里?

标签: algorithm python-3.x csv file-io whitespace


【解决方案1】:

为避免出现双换行符,您可以先从从文件读取的每一行中删除任何 '\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']]

【讨论】:

  • 注意:您需要从f.write 调用中删除+ "\n",或者您只是可靠地双换行。 :-)
【解决方案2】:

您可能(只是猜测,因为您的问题不是 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

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多