Joe
Joe

Reputation: 25

When writing a list to a .txt file with python, '\n' (backslash n) appear?

The result of my script is not as expected. I want to be able to write a word in each line in a .txt then read them into my script add something to them then output them to a PowerShell script.

The first thing I did not expect was the \n which I think is from the line shifting in the .txt. What is the best way to remove it?

The second thing is the first and the last [ ] which is less of a surprise but I still don't know how to filter it out. What would be the best way for that?

I'm new and self thought in python/coding so apologies if the code is a bit messi.

This is my code:

txt_list = []
new_txt_list = []
def StringDeleter(read_path):
    with open(read_path, 'r') as read_txt:
        for line in read_txt:
            line = str(line)
            txt_list.append(line)
    for input in txt_list:
        input1 = "-" + input
        input2 = "." + input
        input3 = "-[" + input + "]"
        input4 = ".[" + input + "]"
        input5 = "[" + input + "]"
        input6 = input
        new_txt_list.append(input1)
        new_txt_list.append(input2)
        new_txt_list.append(input3)
        new_txt_list.append(input4)
        new_txt_list.append(input5)
        new_txt_list.append(input6)
StringDeleter(r"C:\Users\user\Desktop\123.txt")
with open(r"C:\Users\user\Desktop\Temp.PowerShell.ps1", "w") as temp_ps_script:
    temp_ps_script.write(str(new_txt_list))

This is the input file '123.txt':

String1
String2

This is the output file 'Temp.PowerShell.ps1':

['-String1\n', '.String1\n', '-[String1\n]', '.[String1\n]', '[String1\n]', 'String1\n', '-String2', '.String2', '-[String2]', '.[String2]', '[String2]', 'String2']

Upvotes: 0

Views: 66

Answers (1)

Stubbs
Stubbs

Reputation: 193

If they are on the end or start of the strings, you can use strip() but if you would just like to remove all \n's from the strings try this.

line = line.replace('\n','')

replace()

Upvotes: 3

Related Questions