W
W
WithoutNickname2020-01-03 20:51:55
Python
WithoutNickname, 2020-01-03 20:51:55

How to get the content of a specific line of each file?

There are a large number of .txt data files. From each file, you need to get the contents of the second line, how to implement this? Can you please provide a python script?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kokapuk, 2020-01-03
@WithoutNickname

I created a text document called veg, here is its content:
eggplant
pear
apple
potato
Here is my solution to your problem:

f = open(r'veg.txt', 'r', encoding='utf-8')
text = f.read().split('\n')
print(text[1])

Conclusion: pear
Let me explain what I did. We open the veg.txt file with the 'r' argument, and this is reading, we create the text variable and write to it: f.read() we read the file, and split('\n') we split the text that we received from the document , into lines, and in fact now the text variable is a list, so when I output, I refer to the first index, and this is the second element of the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question