Advertisement
earlution

Extract_line_from_text_file.py

Oct 6th, 2023
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. # Specify the name of the input text file
  2. input_file_name = "example.txt"
  3.  
  4. # Specify the line number you want to extract (4 for the 5th line)
  5. line_number_to_extract = 4
  6.  
  7. # Initialize a variable to store the extracted line
  8. extracted_line = None
  9.  
  10. # Open the text file for reading
  11. with open(input_file_name, "r") as file:
  12.     # Iterate over the lines in the file
  13.     for current_line_number, line in enumerate(file):
  14.         # Check if the current line number matches the line to extract
  15.         if current_line_number == line_number_to_extract:
  16.             extracted_line = line.strip()  # Remove leading/trailing whitespace
  17.  
  18. # Check if the line was found and extracted
  19. if extracted_line is not None:
  20.     print(f"Extracted line {line_number_to_extract + 1}: {extracted_line}")
  21. else:
  22.     print(f"Line {line_number_to_extract + 1} not found in the file.")
  23.  
Tags: list file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement