如何使列表接受/n,以便在写入文件时,不是所有内容都在同一行上?

2024-06-28 11:13:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这是我的随机序列号生成器代码,我不知道如何让每个序列号出现在不同的一行,因为它们之间只有空格,我怎么让它们出现在新的一行

#!/usr/bin/python
import random, hashlib, os
from sys import exit
from time import sleep
database_check1 = os.path.expanduser('~/Codemaker/database.txt')
codemaker_dir_check1 = os.path.expanduser('~/Codemaker')
database_check = os.path.isfile(database_check1)
codemaker_dir_check = os.path.isdir(codemaker_dir_check1)

if codemaker_dir_check == True:
    pass
else:
    os.system('mkdir ~/Codemaker')

def choice():

    if database_check == True:
        replace_or_no = raw_input('Warning database.txt already exists   do   you want to relace it? y = yes n=no a = add more to end of file.       y/n/a?:   ')
        if replace_or_no == ('y'):
            os.system('rm ~/Codemaker/database.txt')
            os.system('> ~/Codemaker/database.txt')              

        elif replace_or_no == ('a'):
            pass
        elif replace_or_no == ('n'):
            print('We did not change the database :)')
            exit()

        else:
            print('An error has occured you probably pressed the wrong         button     if you wish to try again it should work')
            exit()
    else:
        os.system('> ~/Codemaker/database.txt')

Acceptable_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
gencodelist = []
choice()
database_file_append1 = os.path.expanduser('~/Codemaker/database.txt')
database_file_append = open(database_file_append1, 'a')



def gencode():
    for i in ('hih'):
        for i in ('hihi'):
            gencodelist.append(random.choice(Acceptable_letters))

        gencodelist.append('-')
    for i in ('hihi'):
        gencodelist.append(random.choice(Acceptable_letters))

    gencodelist.append(' ')

for x in xrange(0, 100):
    gencode()
    gencodeout = ''.join(gencodelist)
    print(gencodeout)
    database_file_append.write(gencodeout)
message = ['100 codes have generated and been written to database.txt  located  in ', database_file_append1, '! :)']
finalmessage = "".join(message)
print(finalmessage)

Tags: pathnointxtifoscheckdir
2条回答

'\n'用于在两行之间创建一个空格,'\r'用于模拟回车或回车键。它可以附加、连接等。。。按以下方式添加到任何字符串my_str+='\n''\n'.join(my_list)、'.join(str(x)+'\n'表示我的\u列表中的x)`等。你有什么问题

替换

gencodelist.append(' ')

gencodelist.append('\n')

它在代码更改后工作

相关问题 更多 >