Reputation:
I have written the following code to generate a random 12 number string:
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?
Upvotes: 0
Views: 216
Reputation: 46
The code below will output random strings (using the code you provided) to a CSV file.
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. 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)
Upvotes: 1