【问题标题】:Write to same line of file in Python在 Python 中写入同一行文件
【发布时间】:2015-02-19 13:14:27
【问题描述】:

我正在尝试编写一个程序来生成用于在我正在开发的游戏中注册帐户的密钥。
到目前为止,我的所有东西都可以处理打印,但是在尝试写入文件时遇到了困难。

这是我当前的代码:

import random
file = open('keys.txt', 'w')
chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
keys = 0
while keys <= 50:
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('-', end='')
    for i in range(0,4):
        print(random.choice(chars), end='')
    print('')    
    keys += 1
file.close()

为了让它打印到文件中,我尝试在 for 循环中的 print 下面添加 file.write(random.choice(chars), end=''),但是我收到了一个 TypeError 说 write() takes no keyword arguments

为了澄清,代码如下所示:

for i in range(0,4):
    print(random.choice(chars), end='')
    file.write(random.choice(chars), end='')
print('-', end='')

通过搜索,我认为问题与 file.write 中的 end='' 有关,但我不确定。有什么想法吗?

提前致谢。

【问题讨论】:

  • 请注意,您的程序存在错误。 10 不是单个字符。

标签: python file input output


【解决方案1】:

print 函数将其参数加上行尾 写入文件。由于在某些情况下您不希望行结束,因此您可以通过明确说出 print("string", end = '') 来覆盖此 默认参数

write 函数只写入它的参数。它不知道线路末端或其他魔法。因此,您不得向它传递这样一个额外的参数。

如果您的程序寿命更长,您应该将其结构化,使其看起来更简洁。以下代码还修复了您的“字符”10,实际上是 2 个字符。

import random
import string

def generateRandomKey():
  alphabet = string.ascii_uppercase + string.digits
  rnd = ''.join(random.choice(alphabet) for _ in range(16))
  return '%s-%s-%s-%s' % (rnd[0:4], rnd[4:8], rnd[8:12], rnd[12:16])

file = open('keys.txt', 'w')
for _ in range(50):
  file.write('%s\n' % generateRandomKey())
file.close()

【讨论】:

    【解决方案2】:

    end=""print 函数的参数,而不是write

    但是你可以试试这个:

    file.write(str(random.choice(chars))+"\n")
    

    将其设置到正确的位置,然后它会像 print 函数一样打印它们。

    【讨论】:

    • 啊,以为是问题所在。我怎样才能打印到文件写入的同一行,就像end='' 在打印函数中一样?
    • 你想同时写它们吗?
    • write() 默认情况下不附加换行符。所以,如果你想要一个新行,你已经明确地包含它。
    【解决方案3】:

    好的,因为我想生成 16 位密钥,所以我将 4 个字符块写入文件,中间有破折号,然后我在 for 循环块的末尾做了file.write('\n')

    感谢大家的回答,他们很有帮助!

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多