PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

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

 August 18, 2022     csv, loops, output, python, random     No comments   

Issue

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?


Solution

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)


Answered By - Steve Bremer
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing