'python string to list with delimiter

Cant post the picture so i'll describe it as precise as possible:

  • 001.txt contains -> a b c ...
  • 002.txt contains -> d e f ...
  • 003.txt contains -> g h i ...
  • etc.

  • 001 002 003
  • a----d----g
  • b----e----h
  • c----f-----i

the data from above should look like a chart in the end in Excel (.csv)

My skills are very very limited or not even there. Maybe someone here to give me a fast explanation or some type of help. First time chatter so dont be to hard on me :D

started to code something like this

with open("001.txt", "r") as f, open("002.txt", "r") as f, open("003.txt") as f:
lines = f.read().split(',')

for line in lines:
    print(line)

My solution thanks to AKX

import csv

filelist = ["001.txt", "002.txt", "003.txt"]
destinationfile = "meine.csv"
dictionary = {}

for file in filelist:
    split = file.split(".", 1)
    header = split[0]
    readfile = open(file, "r")
    tlist = []
    for line in readfile:
        split_line = line.split()
        for split in split_line:
            tlist.append(split)
    dictionary.update({header: tlist})

with open(destinationfile, "w", newline='') as csv_file:
     writer = csv.writer(csv_file,dialect='excel',delimiter=";")
     headers = list(dictionary)
     writer.writerow(headers)
     for entry in zip(*dictionary.values()):
         writer.writerow(entry)


Solution 1:[1]

It's somewhat hard to tell whether a, b, c etc. are separate lines in each file, so I'm not quite able to help with the file-reading code.

However, you can use the zip(*...) idiom to transpose lists of values.

Assuming all of your files are the same length, once you have loaded the text from the files into a dict as below, you can do the printing with

data = {"001": ["a", "b", "c"], "002": ["d", "e", "f"], "003": ["g", "h", "i", "j"]}

headers = list(data)
print(*headers)
for row in zip(*data.values()):
    print(*row)

– the output is

001 002 003
a d g
b e h
c f i

If the data isn't the same length, you can use zip_longest from itertools:

for row in itertools.zip_longest(*data.values(), fillvalue="-"):
    print(*row)

and the output is

001 002 003
a d g
b e h
c f i
- - j

Solution 2:[2]

Take the files to list

file_list = [
    "001.txt", "002.txt", "003.txt"
]

for file in file_list:
    with open (file, "r") as f:
        for line in f:
            print(line)

Solution 3:[3]

filelist = ["001.txt", "002.txt", "003.txt"]
destinationfile = "ergebnis.csv"
print(filelist)
for file in filelist:
    print(file)
    readfile = open(file, "r")
    print(readfile.read())

How about something like this?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 CN-LanBao
Solution 3 papapixxel