简体   繁体   English

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

[英]How to loop print output and write each result to csv?

I have written the following code to generate a random 12 number string:我编写了以下代码来生成一个随机的 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

How can I loop it and save each string output to a .csv file?如何循环它并将每个字符串输出保存到 .csv 文件?

The code below will output random strings (using the code you provided) to a CSV file.下面的代码将随机字符串(使用您提供的代码)输出到 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 files often have column headers, so I included that in the code example. CSV 文件通常具有列标题,因此我将其包含在代码示例中。 You could easily change the function definition to exclude a column header and explicitly define the number of columns when the function is called, like this:您可以轻松更改函数定义以排除列标题并在调用函数时显式定义列数,如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM