我有一個包含在這種格式號的文件:如何使用Python替換隨機文件中的數字?
78 23 69 26 56 59 74 45 94 28 37
62 52 84 27 12 95 86 86 12 89 92
43 84 88 22 31 25 80 40 59 32 98
(所有數字爲在記事本++單個包裝線,它包含的2位數字組1,5k,與之間的空間)
我想要做的是每次運行Python代碼時隨機化一些數字,因此第二個.tmp文件將是唯一的,但保持相同的格式。
所以我嘗試了這個工作,但使用靜態數字:12作爲搜索和55作爲目標。
infile = open('file.txt', 'r')
outfile = open('file.txt.tmp', 'w')
for line in infile:
outfile.write(line.replace('12', '55'))
infile.colse()
outfile.colse()
然而,爲了更好地隨機化,我想要做的是10-99之間使用隨機數,而不是靜態的數字像12和55
所以我試圖做(和失敗)正在取代靜態的12個55號,以隨機的人那樣:
randnum1 = randint(10,99)
randnum2 = randint(10,99)
infile = open('file.txt', 'r')
outfile = open('file.txt.tmp', 'w')
for line in infile:
outfile.write(line.replace(randnum1, randnum2))
而且我得到這個錯誤:
Traceback (most recent call last):
File "<pyshell#579>", line 2, in <module>
outfile.write(line.replace(randnum1, randnum2))
TypeError: Can't convert 'int' object to str implicitly
使用str。 outfile.write(line.replace(str(randnum1),str(randnum2))) – Kajal
我會說str(randnum1),str(randum2)因爲replace需要一個字符串。 – Philipp
請注意,'randnum1'和'randnum2' ints,replace會使用字符串。使用'str(randnum1)'和'str(randnum2)' – vmg