如何正确创建新文件并对其应用多行输入?
How do I properly create new files and apply multiple lines of input to it?
我正在尝试创建 3 个不同的文件,然后尝试打印 10 个随机字母以在文件中打印 3 次。
这是我的代码:
import string
import random
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
line = 0
while line < 3:
for j in range(10):
myStr = random.choice(string.ascii_lowercase)
f.write(myStr)
line = line + 1
并输出:
dfzanwalkccdipukrbwsrzrbheceqi
我试图通过在文件写入中包含换行符来打印它们,但它却打印了 30 行,每行一个字母。感谢您的帮助!
在行循环中写换行符,而不是字符循环。
你也可以把while line < 3:
改成for line in range(3):
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
for line in range(3):
for j in range(10):
myStr = random.choice(string.ascii_lowercase)
f.write(myStr)
f.write("\n")
您也可以使用 random.choices()
一次获取 10 个随机字符,而不是循环。
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
for line in range(3):
myStr = "".join(random.choices(string.ascii_lowercase, k=10))
f.write(myStr + "\n")
我正在尝试创建 3 个不同的文件,然后尝试打印 10 个随机字母以在文件中打印 3 次。 这是我的代码:
import string
import random
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
line = 0
while line < 3:
for j in range(10):
myStr = random.choice(string.ascii_lowercase)
f.write(myStr)
line = line + 1
并输出:
dfzanwalkccdipukrbwsrzrbheceqi
我试图通过在文件写入中包含换行符来打印它们,但它却打印了 30 行,每行一个字母。感谢您的帮助!
在行循环中写换行符,而不是字符循环。
你也可以把while line < 3:
改成for line in range(3):
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
for line in range(3):
for j in range(10):
myStr = random.choice(string.ascii_lowercase)
f.write(myStr)
f.write("\n")
您也可以使用 random.choices()
一次获取 10 个随机字符,而不是循环。
for i in range(3):
with open('data%i.txt' % i, 'w+') as f:
for line in range(3):
myStr = "".join(random.choices(string.ascii_lowercase, k=10))
f.write(myStr + "\n")