Sam Bates
Sam Bates

Reputation: 2817

Selecting first part of a text file in Python

In the process of making a program, I came across the need to read the first value of a text file. I have tried to put each value onto it's own line and read the first line such as in this code, but it would never load the part of the text file I wanted shown in this code:

l = open('output.txt').read()

words = l.split()

for word in words:
    print(word)

open("output.txt", 'wt').write(l)


with open('output.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)

open("output.txt", 'wt').write(word)

q = open("output.txt")

for x, line in enumerate(q):
    if x == 0:
        print (line)

How am I able to do this?

Upvotes: 1

Views: 490

Answers (2)

Vipul
Vipul

Reputation: 4178

If you have every content in separate lines in the text file then you can try:

with open("test.txt") as f:
    data = f.read().splitlines()

here data is a list which contains the content of the text file extracted line by line

for eg: the text file contains data like

Lamborghini Gallardo

Audi

Ferrari

then the above code will give: data=['Lamborghini Gallardo', 'Audi', 'Ferrari']

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239653

Store the contents one element a line and then do this

with open("Input.txt") as in_file:
    data = next(in_file)

now data will have the first line.

This works because open function returns an object of file type, which is iterable. So, we iterate it with next function to get the first line.

Upvotes: 1

Related Questions