Python在没有\ n的情况下编写换行符

时间:2015-10-24 10:38:33

标签: python database python-2.7 text append

嘿我需要将一个字符串写入文本文件,但我需要它没有\ n,因为我将它用作数据库。该脚本工作正常但实际上并没有真正写入换行符,因为我strip() - 编辑它。我想知道即使用另一种语言也有办法解决。 到目前为止我试过了:

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 

我不想使用\ n的原因是因为这段代码:

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

上面的代码将用\ n打印出字符串。有没有办法解决这个问题? 例如,如果pass.txt中有asdf,则print repr(x)将打印为asdf \ n。我需要它来打印asdf

2 个答案:

答案 0 :(得分:1)

据我所知,你要求的是不可能的,因为换行符 \n

为了澄清,文本文件包含字符序列。将它们划分为行的唯一方法是使用一个或多个字符作为行尾标记。所有\n都是。 (有关详细信息,请参阅this answer建议的@Daniel's comment。)

所以你可以不用换行编写,但你的文件将是一个loooong行。如果您想要使用repr()显示其内容但又不想看到换行符,则在打印之前您必须将其删除:

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)

如果这不能解决您的问题,那么您的问题实际上没有解决方案,您需要针对您尝试生成的文件的最终目的提出另一个问题。有人会指出一个解决方案而不是"写一个新行而不用写新行"。

答案 1 :(得分:0)

您可以定义为文件写一行 例如:

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()

如果您接着阅读DummyFile.txt,则不会在文本中看到\n