简体   繁体   English

将随机Python数据写入CSV文件

[英]Write random Python data to CSV file

I have a small python script that uses a library to generate random dates(mm/dd/yyyy) and random time based on a 12 hour clock.. 我有一个小的python脚本,它使用一个库来生成基于12小时制的随机日期(mm / dd / yyyy)和随机时间。

def randomPhone():
    n ='0000000000'
    while '0' in n[3:6] or n[3:6]=='000':
    n = str(random.randint(10**9, 10**10-1))
    return n[:3] + '-' + n[3:6] + '-' + n[6:]
    randomPhone ()

def strTimeProp(start, end, format, prop):
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))
    ptime = stime + prop * (etime - stime)
    return time.strftime(format, time.localtime(ptime))

def randomDate(start, end, prop):
    return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop)

print randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())

I have code to generate other random data, like names, and phone numbers. 我有代码来生成其他随机数据,例如姓名和电话号码。 But first I want to write the date and time to a CSV file and make sure the formatting is correct. 但是首先我想将日期和时间写入CSV文件,并确保格式正确。 So the date and time are correctly displayed in a nicely formatted table, however when I try to add in the phoneNumber() argument I run into problems. 因此,日期和时间正确显示在格式良好的表中,但是当我尝试添加phoneNumber()参数时,我遇到了问题。 The table displays when only the Date/Time argument is passed, and how I want it to looks, but with another section added onto the end for a Phone#, etc. 该表仅在传递日期/时间参数时显示,并且我希望它看起来如何,但在电话号等末尾添加了另一部分。

f = open("CDR.csv", 'wt')
try:
    writer = csv.writer(f)
    writer.writerow( ('Date/Time', 'Phone#') )
    for i in range(1):
        writer.writerow( (randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random())), randomPhone() )
finally:
    f.close()

print open("CDR.csv", 'rt').read()

However I'm getting a typeError, `writerow() takes exactly one argument and two are given' 但是我得到一个typeError,`writerow()恰好接受一个参数,给出两个参数。

I'm following CSV Writing as an example. 我以CSV Writing为例。

You've got your parentheses in the wrong place, causing you to pass two arguments to .writerow() instead of a single tuple. 您将括号放在错误的位置,导致您将两个参数传递给.writerow()而不是单个元组。

Try separating your tuple creation from the function call. 尝试将元组创建与函数调用分开。 This should make the code easier to read. 这应该使代码更易于阅读。

row = (
    randomDate("1/1/2016 12:00 AM", "1/1/2017 12:00 AM", random.random()), 
    randomPhone(),
)
writer.writerow(row)

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

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