[英]Python write newline without \n
嘿,我需要將一個字符串寫入文本文件,但是我需要它不具有\\ 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,則打印repr(x)將輸出asdf \\ n。 我需要它來打印asdf
據我所知,您的要求是不可能的,因為換行符是 \\n
!
為了明確起見,文本文件包含字符序列。 將它們划分為行的唯一方法是使用一個或多個字符作為行尾標記。 僅此\\n
。 (有關更多詳細信息,請參見@Daniel的評論建議的此答案 。)
因此,您可以編寫不帶換行符的文件,但是您的文件將僅占一行。 如果要使用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)
如果那不能解決您的問題,那么您的問題確實沒有解決方案,您需要針對要生成的文件的最終目的詢問另一個問題。 除了“不用換行就寫換行”以外,還會有人為您提供解決方案。
您可以定義一個行來寫一個文件。
例如:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.