简体   繁体   中英

Python write newline without \n

Hey I need to write a string to a text file but i need it to not have a \\n as I am using it as a database. The script works fine but doesnt actually write into a newline obviously because I strip()-ed it. I was wondering if there was a way around even in another language. So far I tried:

textfile = open('pass.txt.','a')
ask = raw_input("[+] Do you want to append you own passwords(y/n)")
if ask == "y":
    print "[+] Use quit_appender_now to quit adding string"
    while True:
        stri = raw_input("[+] Enter word to add-->")
        if stri == "quit_appender_now":
            break
        else:
            stri = stri + "\n"
            textfile.write(stri.strip())
elif ask =="n":
    pass 

The reason I dont want to use \\n is because of this code:

with open('pass.txt'),'r') as r_text:
    for x in r_text:
        print repr(x)

The above code will print out the string with \\n. Is there any way to get around this? For example if pass.txt had asdf in there print repr(x) would print asdf\\n. I need it to print asdf

As far as I can tell, what you are asking for is impossible because a newline is \\n !

To clarify, text files contain sequences of characters. The only way to divide them into lines is to use one or more characters as the end-of-line marker. That's all \\n is. (See this answer , suggested by @Daniel's comment , for more details.)

So you can write without newlines, but your file will be one loooong line. If you want to display its contents with repr() but don't like seeing the newline, you'll have to strip it before you print it:

with open('pass.txt'),'r') as r_text:
    for x in r_text:
        x = x.rstrip("\n")   # Don't discard spaces, if any
        print repr(x)

If that doesn't solve your problem, then your problem really has no solution and you need to ask a different question about the ultimate purpose of the file you're trying to generate. Someone will point you to a solution other than "writing a newline without writing a newline".

You could make a definition to write a line to a file.
For example:

class Dummy():
    def __init__(self):
        print('Hello')
        self.writeToFile('Writing a line')
        self.writeToFile('Writing another line')

    def writeToFile(self, value):
        self.value = value 
        # Open file 
        file = open('DummyFile.txt', 'a')
        # Write value to file. 
        file.write(value)
        # Jump to a new line. 
        file.write('\n')
        # close file 
        file.close()

Dummy()

If you then would read DummyFile.txt , you will not see the \\n in the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM