Unwanted line break in the middle of string output (Python)

Question:

I have a simple Python script with 3 loops. The loops itself are working without any issue, but I noticed that just the last loop is printing the output in the correct way. The iterations before are showing a line break in the middle of the string, and I don’t understand where it is coming from.

# Open the file containing the Keywords
with open('keyword.txt', 'r') as keyword_file:
    keywords = keyword_file.readlines()
# Open the file containing the Numbers
with open('number.txt', 'r') as number_file:
    numbers = number_file.readlines()

# Loop over each keyword + number + iteration
# outer loop - keywords
for keyword in keywords:
    # nested loop - numbers
    for number in numbers:
        # nested loop - to iterate from 1 to 10
        for j in range(1,11):
            # print combined string
            text = "Keyword: " + str(keyword) + " Number: " + str(number) + " Iteration: " + str(j)
            print (text)

            # Open a new file to write the combined string
            with open('target.txt', 'a') as target_file:
                # Write each string to the file on a new line
                target_file.write(text + 'n')

The loaded text files are quite basic:

keyword.txt

Word_A
Word_B
Word_C

number.txt

1111
2222
3333

The output in the terminal and also in the target.txt looks like this.

How can I get a clean output per line?

Asked By: x0100

||

Answers:

The issue here because it’s reading the break lines as well from the file, which will be the last character in each line, to get rid of them, do the following:

with open('keyword.txt', 'r') as keyword_file:
    keywords = keyword_file.readlines()
    keywords = [keyword[:-1] for keyword in keywords]
# Open the file containing the Numbers
with open('number.txt', 'r') as number_file:
    numbers = number_file.readlines()
    numbers = [number[:-1] for number in numbers]
Answered By: Kasper

The issue is that the strings you’re reading from the file have newlines in them, so you need to run .strip() on those strings you’re reading to get rid of the leading or trailing whitespace.

Also, it’s bad practice to open and close a file repeatedly inside a loop. Instead, open it once and put the loop inside of the with-block.

Also, you don’t have to convert the lines you read from the line into a string with str() because they’re already strings. And, you can make your string concatenation a lot nicer with f-strings:

# Open the file containing the Keywords
with open('keyword.txt', 'r') as keyword_file:
    keywords = keyword_file.readlines()
# Open the file containing the Numbers
with open('number.txt', 'r') as number_file:
    numbers = number_file.readlines()

# Open a new file to write the combined string
with open('target.txt', 'a') as target_file:
    # Loop over each keyword + number + iteration
    # outer loop - keywords
    for keyword in keywords:
        # nested loop - numbers
        for number in numbers:
            # nested loop - to iterate from 1 to 10
            for j in range(1,11):
                # print combined string
                text = f"Keyword: {keyword.strip()} Number: {number.strip()} Iteration: {j}"
                print(text)

                # Write each string to the file on a new line
                target_file.write(text + 'n')
Answered By: Michael M.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.