2015-10-24 38 views
0

嘿我需要寫一個字符串到一個文本文件,但我需要它沒有\ n,因爲我正在使用它作爲數據庫。該腳本工作正常,但實際上並沒有寫入新行,顯然是因爲我剝離() - 編輯它。我想知道是否有其他語言的解決方法。 到目前爲止,我嘗試:Python不寫 n

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,則打印repr(x)將打印asdf \ n。我需要它打印asdf

+0

使用'x.strip()'? – hjpotter92

+2

「如果你希望你的數據顯示在不同的'行'上,你必須在它們之間放置一個行分隔符,這就是'\ n'字符的全部。」閱讀你的問題在這裏的整個答案:http://stackoverflow.com/a/18065656/2039173 –

+0

Nah我編碼第二隻是爲了說明我的觀點。真正的原因要複雜得多,而且不會解決這個問題 –

回答

1

據我所知,你所要求的是不可能的,因爲換行\n

爲了澄清,文本文件包含字符序列。將它們分成行的唯一方法是使用一個或多個字符作爲行尾標記。這就是全部\n是。 (有關更多詳細信息,請參見this answer,由@Daniel's comment建議)。

因此,您可以不使用換行符編寫代碼,但是您的文件將只有一行。如果你想與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) 

如果不真正解決你的問題,那麼你的問題沒有解決方案,您需要針對您要生成的文件的最終目的提出不同的問題。有人會指出你的解決方案,而不是「寫一個新行,不寫一個換行符」。

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