2

I have a test.txt file that contains:

yellow.blue.purple.green
red.blue.red.purple

And i'd like to have on output.txt just the second and the third part of each line, like this:

blue.purple
blue.red

Here is python code:

with open ('test.txt', 'r') as file1, open('output.txt', 'w') as file2:
    for line in file1:
        file2.write(line.partition('.')[2]+ '\n')

but the result is:

blue.purple.green
blue.red.purple

How is possible take only the second and third part of each line?

Thanks

2 Answers 2

3

You may want

with open('test.txt', 'r') as file1, open('output.txt', 'w') as file2:
    for line in file1:
        file2.write(".".join(line.split('.')[1:3])+ '\n')

When you apply split('.') to the line e.g. yellow.blue.purple.green, you get a list of values

["yellow", "blue", "purple", "green"]

By slicing [1:3], you get the second and third items.

Sign up to request clarification or add additional context in comments.

Comments

0

First I created a .txt file that had the same data that you entered in your original .txt file. I used the 'w' mode to write the data as you already know. I create an empty list as well that we will use to store the data, and later write to the output.txt file.

output_write = [] 

with open('test.txt', 'w') as file_object:
    file_object.write('yellow.' + 'blue.' + 'purple.' + 'green')
    file_object.write('\nred.' + 'blue.' + 'red.' + 'purple')   

Next I opened the text file that I created and used 'r' mode to read the data on the file, as you already know. In order to get the output that you wanted, I read each line of the file in a for loop, and for each line I split the line to create a list of the items in the line. I split them based on the period in between each item ('.'). Next you want to get the second and third items in the lines, so I create a variable that stores index[1] and index[2] called new_read. After we will have the two pieces of data that you want and you'll likely want to write to your output file. I store this data in a variable called output_data. Lastly I append the output data to the empty list that we created earlier.

with open ('test.txt', 'r') as file_object:
    for line in file_object:
        read = line.split('.')
        new_read = read[1:3]
        output_data = (new_read[0] + '.' + new_read[1])
        output_write.append(output_data)

Lastly we can write this data to a file called 'output.txt' as you noted earlier.

with open('output.txt', 'w') as file_object:
    file_object.write(output_write[0])
    file_object.write('\n' + output_write[1])
    print(output_write[0])
    print(output_write[1])

Lastly I print the data just to check the output:

blue.purple
blue.red

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.