Keep tabulation when reading a txt file

Viewed 100

I'm using this function to take a file in a list:

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

I have to modify this list and write that in another file.

This code doesn't keep the tabulation. How can I solve this issue?

2 Answers

try checking for tabs in the cycle:

    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

Found this solution:

def leggi_file_in_stringa (file_name):
list = []
with open (file_name,'r') as file:
    for line in file:
        first_time = True
        for word in line.split(" "):
            if first_time != True:
                list.append (" ")
            first_time = False
            list.append(word)
file.close()
return list

The "first_time" value is because without it there would be a extra space at the beginning of every line

Related