因此,我试图将所有这些信息都写入.txt文件,但是由于名称是从.txt文件中提取的,因此
利亚姆
诺亚
威廉
等...
当我写入文件时,它会将名字和姓氏与其他所有内容分隔开。
我一直在寻找StackOverflow的解决方案,但找不到足够具体的东西。
password = input('Enter the Password you would like to use ')
open('names.txt', 'r+')
lines = open("names.txt").readlines()
firstName = lines[0]
words = firstName.split()
firstNameChoice = random.choice(lines)
open('names.txt', 'r+')
lines = open("names.txt").readlines()
lastName = lines[0]
words = lastName.split()
lastNameChoice = random.choice(lines)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(firstNameChoice)
accountFile.write(lastNameChoice)
accountFile.write(randomNumber)
accountFile.write('@')
accountFile.write(catchall)
accountFile.write(':')
accountFile.write(password)
accountFile.write('\n')
signUp()
Expectation would be everything printed to one line but that's not the case.
答案 0 :(得分:1)
作为快速解决问题的方法,可以将所有编写的命令合并为一行:
with open('accounts.txt', 'a') as accountFile: # using a context manager is highly recommended
# with spaces
accountFile.write('{} {} {} @ {} : {} \n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
# without spaces
accountFile.write('{}{}{}@{}:{}\n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
答案 1 :(得分:0)
如果我的理解正确,那么您希望将所有内容写成一行。
您正在写入文件的同时包含\n
的变量。
因此,您必须将其替换为' '
。将此代码替换为您的程序,例如:
accountFile.write(firstNameChoice.replace('\n',' '))
accountFile.write(lastNameChoice.replace('\n',' '))
accountFile.write(str(randomNumber).replace('\n',' '))
accountFile.write('@'.replace('\n',' '))
#accountFile.write(catchall)
accountFile.write(':'.replace('\n',' '))
accountFile.write(str(password).replace('\n',' '))
现在它将像这样WilliamWilliam448@:dsada
顺便说一句,我不知道您所说的catchall
答案 2 :(得分:0)
将所有内容都放在换行符上的原因是因为您的姓名字符串的末尾包含“ \ n”,因为它具有换行符。有一个简单的解决方法。
在定义名字和姓氏变量的位置末尾添加.rstrip()
。像这样:
firstNameChoice = random.choice(lines).rstrip()
lastNameChoice = random.choice(lines).rstrip()
答案 3 :(得分:0)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(f'{firstNameChoice} {lastNameChoice} {randomNumber} @ {catchall}: {password} \n')