Home >Backend Development >Python Tutorial >How to Add Quotes and Commas to Each Line in a Text File Using Python
Processing text files is a common task in programming, whether it’s for data cleaning, preparation, or formatting. In this tutorial, we’ll explore how to use Python to modify a .txt file by adding double quotes (") around each line and a comma (,) at the end.
This step-by-step guide will help you process your text file efficiently, regardless of its size.
Suppose you have a .txt file containing 5159 lines, where each line represents a phrase. Your goal is to:
Add double quotes (") around the phrase on each line.
Append a comma (,) at the end of each line.
Save the modified lines into a new file.
Hello World Python
"Hello", "World", "Python",
Here’s how you can accomplish this task using Python.
The first step is to read the contents of the .txt file. Python’s built-in open() function allows you to easily read lines from a file.
Using Python’s string formatting, we’ll add the required double quotes and comma to each line.
Finally, write the processed lines into a new file to preserve the original data.
Below is the complete Python script to perform the task:
# File paths input_file = "input.txt" # Replace with your input file path output_file = "output.txt" # Replace with your desired output file path # Step 1: Read the input file with open(input_file, "r") as file: lines = file.readlines() # Step 2: Process each line processed_lines = [f'"{line.strip()}",\n' for line in lines] # Step 3: Write to the output file with open(output_file, "w") as file: file.writelines(processed_lines) print(f"Processed {len(lines)} lines and saved to {output_file}.")
with open(input_file, "r") as file: lines = file.readlines()
processed_lines = [f'"{line.strip()}",\n' for line in lines]
line.strip() removes any leading or trailing whitespace or newline characters from each line.
f'"{line.strip()}",n' formats each line by wrapping it in double quotes and appending a comma, followed by a newline character (n).
with open(output_file, "w") as file: file.writelines(processed_lines)
python -m process_text
If your input file contains:
Hello World Python
The output file will look like:
Hello World Python
Using Python, you can quickly and efficiently modify text files, even when they contain thousands of lines. The code is simple, reusable, and can be adapted to perform other text-processing tasks.
This solution is particularly useful for preparing data for programming tasks, such as importing data into a database or generating structured formats like JSON or CSV. With Python, the possibilities are endless!
The above is the detailed content of How to Add Quotes and Commas to Each Line in a Text File Using Python. For more information, please follow other related articles on the PHP Chinese website!