gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
i need python code to take a file and cut the first 500 lines to another file.
- User
i need python code to take a file and cut the first 500 lines to another file.
- Assistant
Certainly! Here's a simple Python script that will take the first 500 lines from an input file and write them to a new output file:
python# Define the input and output file paths input_file_path = 'input_file.txt' output_file_path = 'output_file.txt' # Open the input file and output file with open(input_file_path, 'r') as input_file, open(output_file_path, 'w') as output_file: # Iterate over a range of 500 to go through the first 500 lines for _ in range(500): # Read the next line from the input file line = input_file.readline() # If the line is empty, then we've reached the end of the file before the 500th line if not line: break # Write the current line to the output file output_file.write(line) print('First 500 lines copied to', output_file_path)