![](/img/trans.png)
[英]How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt"
[英]Python How to write 5 lines in one file.txt and the other 3 lines in a new file1.txt with +=1 for example
我想要一个总共生成 12 行的脚本。 一个文件中的 5 行 Numbers.txt 第二个文件中的 5 行 Numbers0001.txt 第三个文件中的 2 行 Numbers0002.txt
有没有人以前处理过这个问题并且可以帮助我?
我的工作代码根据用户输入插入 5 行:
import random
import string
oneFile = open('Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase
for userInput in range(int(input('How many 12 digit keys do you want?'))):
while key_count <= userInput:
key_count += 1
number = random.randint(1, 999)
key = number
text = str(''.join(random.sample(chars*6, 12)))
oneFile.write(text + "\n")
oneFile.close()
这里是我在循环和 If Else 上挣扎的代码:
import random
import string
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase
if key_count > 5:
for userInput in range(int(input('How many 8 digit keys do you want?'))):
while key_count <= userInput:
oneFile = open(key_count('.txt', 'w'))
key_count += 1
number = random.randint(1, 999)
key = number
text = str(''.join(random.sample(chars*6, 8)))
oneFile.write(text + "\n")
oneFile.close()
else:
oneFile = open('Numbers'+ +=1 +'.txt', 'w')
oneFile.write(text + "\n") +5
oneFile.close()
我不确定这是否是您要找的。 我只是拿了一个 12 项的列表(从 1 到 12 的整数)并将它们放入三个文件 Number.txt Numbers001.txt 和 Numbers002.txt
list_of_something = [1,2,3,4,5,6,7,8,9,10,11,12]
counter = 0
while counter < len(list_of_something):
if counter < 5:
oneFile = open("Numbers.txt", 'a')
oneFile.write(str(list_of_something[counter]) + "\n")
oneFile.close()
counter +=1
elif counter >=5 and counter < 10:
oneFile = open("Numbers001.txt", 'a')
oneFile.write(str(list_of_something[counter]) + "\n")
oneFile.close()
counter +=1
else:
oneFile = open("Numbers002.txt", 'a')
oneFile.write(str(list_of_something[counter]) + "\n")
oneFile.close()
counter +=1
输出将是 3 个文件 - 第一个将有列表中的第 1-5 个第 6-10 个和第三个第 11-12 个项目
import random
import string
userInput = 0
key_count = 0
file_count = 0
value_count = 0
chars = string.ascii_uppercase
for userInput in range(int(input('How many 8 digit keys do you want?'))):
while key_count <= userInput:
if key_count % 5 == 0:
file_count += 1
oneFile = open('Numbers000'+ str(file_count) +'.txt', 'w')
key_count += 1
number = random.randint(1, 999)
key = number
text = str(''.join(random.sample(chars*6, 8)))
oneFile.write(text + "\n")
if key_count % 5 == 0:
oneFile.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.