Home > Mobile >  How can I manage on using for loop number into a txt files
How can I manage on using for loop number into a txt files

Time:12-12

Good evening everyone, I am David Tzu a 9years old, May I ask about txt files in python... I currently trying to read the inside .txt files with proper number alignment..

Sample.txt files consist of: One Two Three Four Five Six Seven Eight Nine Ten

here's my code:

with open('Sample.txt', 'r') as f:
    contents = f.readlines()
    for x in range(1, 11):
        print(x, contents)

I would like to get a result the same as this one expected output:

1 One
2 Two
3 Three
4 Four
5 Five
6 Six
7 Seven
8 Eight
9 Nine
10 Ten

I'm really sorry for my bad english hope you all understand what I am trying to convey..

CodePudding user response:

You could change readlines in to readline and move it into the for loop, like the example below:

with open('Sample.txt', 'r') as f:
    for x in range(1, 11):
        print(x, f.readline())

That is assuming there is a new line in your text file between each number.

EDIT TO REMOVE NEWLINE:

with open('Sample.txt', 'r') as f:
    for x in range(1, 11):
        print(x, f.readline().replace("\n",""))

Or similar to Larry the Llamas comment still using readlines:

with open('Sample.txt', 'r') as f:
    contents = f.readlines()
    for x in range(1, 11):
        print(x, contents[x - 1].replace("\n",""))

CodePudding user response:

with open('Sample.txt', 'r') as f:
    for x in range(1, 11):
        print(x, f.readline().strip('\n'))

Try this.

  • Related