Split and print the word before and after the \ of *n of lines, from a txt to two different txt's

58 views Asked by At

I searched around a bit, but I couldn't find a solution that fits my needs. I'm new to python, so I'm sorry if what I'm asking is pretty obvious.

I have a .txt file (for simplicity I will call it inputfile.txt) with a list of names of folder\files like this:

camisos\CROWDER_IMAG_1.mov
camisos\KS_HIGHENERGY.mov
camisos\KS_LOWENERGY.mov

What I need is to split the first word (the one before the \) and write it to a txt file (for simplicity I will call it outputfile.txt).

Then take the second (the one after the \) and write it in another txt file.

This is what i did so far:

 with open("inputfile.txt", "r") as f:
        lines = f.readlines()
    with open("outputfile.txt", "w") as new_f:
        for line in lines:
            text = input()
            print(text.split()[0])

This in my mind should print only the first word in the new txt, but I only got an empty txt file without any error.

Any advice is much appreciated, thanks in advance for any help you could give me.

1

There are 1 answers

2
Ajay On BEST ANSWER

You can read the file in a list of strings and split each string to create 2 separate lists.

with open("inputfile.txt", "r") as f:
    lines = f.readlines()

X = []
Y = []

for line in lines:
    X.append(line.split('\\')[0] + '\n')
    Y.append(line.split('\\')[1])

with open("outputfile1.txt", "w") as f1:
    f1.writelines(X)

with open("outputfile2.txt", "w") as f2:
    f2.writelines(Y)