如何在 Python3 中使用 /n?
How to use /n in Python3?
为了逐行而不是逐行获取输出,我想开始使用 /n 命令。
这是我认为应该放置的代码片段:
password_for = input('This password is for: ')
your_pass = 'Your password for {} is: {}'.format(password_for, password)
save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
file1.write(your_pass)
应该使用 /n 命令来获取应该写入(输出)的文本,像这样逐行:
Input 1
input 2
但是现在输出是这样的:
Input1Input2
也许 /N 不是解决方案?让我知道!
您可以将它与字符串连接运算符一起使用,即“+ 运算符”,如下所示:
file1.write(your_pass + '\n')
password_for = input('This password is for: ')
your_pass = 'Your password for {} is: {}'.format(password_for, password)
save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
file1.write(your_pass + '\n') # You need to place '\n' here.
有些字符必须“转义”才能将它们输入到字符串中。在这种情况下,您需要一个换行符,它写为 \n
in Python.
无论如何,回答你的问题:
with open(completeName, "a+") as file1:
file1.write(your_pass + '\n')
这会将 your_pass
中的字符串与包含一个换行符的字符串连接起来,然后调用 file1.write
.
您只需将此添加到您的代码中:-
+ '\n'
最后一行:-
file1.write(your_pass + '\n')
为了逐行而不是逐行获取输出,我想开始使用 /n 命令。
这是我认为应该放置的代码片段:
password_for = input('This password is for: ')
your_pass = 'Your password for {} is: {}'.format(password_for, password)
save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
file1.write(your_pass)
应该使用 /n 命令来获取应该写入(输出)的文本,像这样逐行:
Input 1
input 2
但是现在输出是这样的:
Input1Input2
也许 /N 不是解决方案?让我知道!
您可以将它与字符串连接运算符一起使用,即“+ 运算符”,如下所示:
file1.write(your_pass + '\n')
password_for = input('This password is for: ')
your_pass = 'Your password for {} is: {}'.format(password_for, password)
save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
file1.write(your_pass + '\n') # You need to place '\n' here.
有些字符必须“转义”才能将它们输入到字符串中。在这种情况下,您需要一个换行符,它写为 \n
in Python.
无论如何,回答你的问题:
with open(completeName, "a+") as file1:
file1.write(your_pass + '\n')
这会将 your_pass
中的字符串与包含一个换行符的字符串连接起来,然后调用 file1.write
.
您只需将此添加到您的代码中:-
+ '\n'
最后一行:-
file1.write(your_pass + '\n')