77.4k views
1 vote
in the following code example, add the necessary code tell python to read and print just the first line of the text file being opened, if the file already exists. import os.path

User Infeligo
by
8.0k points

1 Answer

3 votes

Answer:

Here is one possible way to do that:

```python

import os.path

# check if the file exists

if os.path.isfile("textfile.txt"):

# open the file in read mode

with open("textfile.txt", "r") as f:

# read and print the first line

first_line = f.readline()

print(first_line)

else:

# print an error message

print("The file does not exist.")

```

User Hadvig
by
8.4k points