简体   繁体   中英

reading .txt file in python

I have a problem with a code in python. I want to read a.txt file. I use the code:

f = open('test.txt', 'r')  # We need to re-open the file
data = f.read()

print(data)

I would like to read ONLY the first line from this.txt file. I use

f = open('test.txt', 'r')  # We need to re-open the file
data = f.readline(1)

print(data)

But I am seeing that in screen only the first letter of the line is showing.

Could you help me in order to read all the letters of the line? (I mean to read whole the line of the.txt file)

with open("file.txt") as f:
   print(f.readline())

This will open the file using with context block (which will close the file automatically when we are done with it), and read the first line, this will be the same as:

f = open(“file.txt”)
print(f.readline())
f.close()

Your attempt with f.readline(1) won't work because it the argument is meant for how many characters to print in the file, therefore it will only print the first character.

Second method:

with open("file.txt") as f:
   print(f.readlines()[0])

Or you could also do the above which will get a list of lines and print only the first line.

To read the fifth line, use

with open("file.txt") as f:
   print(f.readlines()[4])

Or:

with open("file.txt") as f:
   lines = []
   lines += f.readline()
   lines += f.readline()
   lines += f.readline()
   lines += f.readline()
   lines += f.readline()
   print(lines[-1])

The -1 represents the last item of the list

Learn more:

Your first try is almost there, you should have done the following:

f = open('my_file.txt', 'r')
line = f.readline()
print(line)
f.close()

A safer approach to read file is:

with open('my_file.txt', 'r') as f:
    print(f.readline())

Both ways will print only the first line.

Your error was that you passed 1 to readline which means you want to read size of 1, which is only a single character. please refer to https://www.w3schools.com/python/ref_file_readline.asp

I tried this and it works, after your suggestions:

f = open('test.txt', 'r')
data = f.readlines()[1]

print(data)

Use with open(...) instead:

with open("test.txt") as file:
    line = file.readline()
    print(line)

Keep f.readline() without parameters.

It will return you first line as a string and move cursor to second line.

Next time you use f.readline() it will return second line and move cursor to the next, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM