Here are several ways to read the first line of a file in Python:
Method 1: Use `readline()`
with open('filename.txt', 'r') as file:
first_line = file.readline()
print(first_line)Note: This method reads the first line of a file until it encounters the '\n' character.
Method 2: Use a for loop
with open('filename.txt', 'r') as file:
for line in file:
first_line = line
break # 退出循环,只获取第一行
print(first_line)Method 3: Use `next()`
with open('filename.txt', 'r') as file:
first_line = next(file)
print(first_line)The core of these methods is to open a file and then extract the content of its first line. It is recommended to use the `with` statement to open the file; this statement automatically closes the file after reading its contents, preventing accidental resource leaks.