如何循环打印输出并将每个结果写入csv?

问题描述 投票:0回答:1

我编写了以下代码来生成一个随机的12数字字符串:

import uuid

def my_random_string(string_length=12):
    """Returns a random string of length string_length."""
    random = str(uuid.uuid4()) # Convert UUID format to a Python string.
    random = random.upper() # Make all characters uppercase.
    random = random.replace("-","") # Remove the UUID '-'.
    return random[0:string_length] # Return the random string.

print(my_random_string(12)) # For example, D9E50Cd

如何循环播放并将每个字符串输出保存到.csv文件?

python loops csv random output
1个回答
0
投票
下面的代码将使用您提供的代码将随机字符串输出到CSV文件。

import csv import uuid def my_random_string(string_length=12): """Returns a random string of length string_length.""" random = str(uuid.uuid4()) # Convert UUID format to a Python string. random = random.upper() # Make all characters uppercase. random = random.replace("-","") # Remove the UUID '-'. return random[0:string_length] # Return the random string. def random_string_to_csv(file_name, column_header, num_rows): num_cols = len(column_header) with open(file_name, mode='w', newline = '') as f: rand_string_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) rand_string_writer.writerow(column_header) for i in range(num_rows): row = [my_random_string() for j in range(num_cols)] rand_string_writer.writerow(row) column_header = ['col1', 'col2', 'col3', 'col4'] num_rows = 5 random_string_to_csv('test.csv', column_header, num_rows)

CSV文件通常具有列标题,因此我将其包含在代码示例中。您可以轻松地更改函数定义以排除列标题,并在调用函数时显式定义列数,如下所示:

def random_string_to_csv(file_name, num_cols, num_rows): with open(file_name, mode='w', newline = '') as f: rand_string_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) for i in range(num_rows): row = [my_random_string() for j in range(num_cols)] rand_string_writer.writerow(row)

© www.soinside.com 2019 - 2024. All rights reserved.