我试图在行[2]中的csv文件的每一行中追加一个随机数我从原始文件中获取信息然后我将其写入新的csv文件+我将第二行附加到随机数 但是当我运行脚本时,我在每一行都得到相同的随机数( 我有读取文件,其中包含exp:
car,golf
当我将这些数据写入新的csv文件并追加第二行时,每行都得到相同的数字
car,golf,1777
car,bmw,1777
car,m3,1777
我怎么能解决这个问题,所以我可以在每一行都有随机数
data = []
with open("read.csv", "r") as the_file:
sid_row = 5000
for i in range(sid_row):
line = str(random.randint(1,5000))
sid = line
reader = csv.reader(the_file, delimiter=",")
for row in reader:
try:
new_row = [row[0], row[1],sid]
data.append(new_row)
except IndexError as error:
print(error)
pass
with open("Random.csv", "w+") as Ran_file:
writer = csv.writer(Ran_file, delimiter=",")
for new_row in data:
writer.writerow(new_row)
答案 0 :(得分:1)
对于您正在处理的每一行,您每次都需要一个新的随机数,例如:
data = []
with open("read.csv", "r") as the_file:
reader = csv.reader(the_file, delimiter=",")
for row in reader:
try:
line = str(random.randint(1,5000))
sid = line
new_row = [row[0], row[1],sid]
data.append(new_row)
except IndexError as error:
print(error)
pass
with open("Random.csv", "w+") as Ran_file:
writer = csv.writer(Ran_file, delimiter=",")
for new_row in data:
writer.writerow(new_row)