读取txt文件时保留制表符

问题描述 投票:3回答:1

我正在使用此功能在列表中获取文件:

def read_file_in_list (file_name):
    list = []
    with open (file_name,'r') as file:
        for line in file:
            lista.append ("\n")
            for word in line.split():
                list.append (" ")
                list.append(word)
    file.close()
    return list

我必须修改此列表并将其写入另一个文件。

此代码未保留列表。我该如何解决这个问题?

python file split whitespace
1个回答
0
投票

尝试在周期中检查选项卡:

    def read_file_in_list (file_name):
        list = []
        with open (file_name,'r') as file:
           for line in file:
                list.append ("\n")
                if line.startswith("\t"):
                    list.append("\t")
                for word in line.split():
                    list.append (" ")
                    list.append(word)
        file.close()
        return list
© www.soinside.com 2019 - 2024. All rights reserved.