2014-08-30 3 views
0

데이터를 생성하는 스크립트를 작성하려고합니다. 나는 이것을 위해 임의의 패키지를 사용하고있다. 나는 스크립트를 실행하고 모든 것이 잘 작동한다. 그러나 결과를 확인해 보면 스크립트가 어떤 이유로 든 마지막 100 개 이상의 행을 생성하지 못하는 것으로 나타났습니다.데이터 생성이 완료되지 않았습니다 : Python random

누군가 이런 일이 일어날 수있는 이유를 제안 할 수 있습니까? ,

result_log.close() 

더 나은를 여전히 상황에 맞는 관리자로 파일 객체를 사용하고 with 문이 때 블록 종료 당신을 위해 그것을 닫고 있습니다

from __future__ import print_function 
from faker import Faker; 
import random; 

## Vaue declaration 
population = 3; 
product = 3; 
years = 3; 
months = 13; 
days = 30; 
tax= 3.5; 

## Define Column Header 
Column_Names = "Population_ID",";","Product_Name",";","Product_ID",";","Year",";", 
"Month",";","Day","Quantity_sold",";","Sales_Price",";","Discount", 
";","Actual_Sales_Price",tax; 


## Function to generate sales related information 
def sales_data(): 
    for x in range(0,1): 
     quantity_sold = random.randint(5,20); 
     discount = random.choice(range(5,11)); 
     sales_price = random.uniform(20,30); 
     return quantity_sold,round(sales_price,2),discount,round((sales_price)-(sales_price*discount)+(sales_price*tax)); 


## Format the month to quarter and return the value 
def quarter(month): 
    if month >= 1 and month <= 3: 
     return "Q1"; 
    elif month > 3 and month <= 6: 
     return "Q2"; 
    elif month > 6 and month <= 9: 
     return "Q3"; 
    else: 
     return "Q4"; 

## Generate product_id 
def product_name(): 
    str2 = "PROD"; 
    sample2 = random.sample([1,2,3,4,5,6,7,8,9],5); 
    string_list = []; 
    for x in sample2: 
     string_list.append(str(x)); 
    return (str2+''.join(string_list)); 


### Main starts here ### 

result_log = open("C:/Users/Sangamesh.sangamad/Dropbox/Thesis/Data Preparation/GenData.csv",'w')  
print (Column_Names, result_log); 

### Loop and Generate Data ### 

for pop in range(0,population):  
    pop = random.randint(55000,85000); 
    for prod_id in range(0,product): 
     product_name2 = product_name(); 
     for year in range(1,years): 
      for month in range(1,months): 
       for day in range(1,31): 
        a = sales_data(); 
        rows = str(pop)+";"+product_name2+";"+str(prod_id)+";"+str(year)+";"+str(month)+";"+quarter(month)+";"+str(day)+";"+str(a[0])+";"+str(a[1])+";"+str(a[2])+";"+str(tax)+";"+str(a[3]); 
        print(rows,file=result_log); 
        #print (rows); 
    tax = tax+1; 
+2

언제든지 'result_log' 파일을 닫고 있습니까? –

+0

참고 : 파이썬은'; '세미콜론을 허용 할 수도 있지만 반드시 필요하지는 않습니다. 그들을 제거하십시오. –

+0

안녕하세요 @MartijnPieters 오류를 지적 해 주셔서 감사합니다. 나는 그것을 닫아야 만 잘 작동한다. 나는 제안에 따라 세미콜론을 제거 할 것이다. 코드의 품질에 대한 의견은 어떻습니까? 의견을 제시하는 것만으로! –

답변

1

당신은 버퍼가 플러시해야 할 파일을 닫아야합니다 :

:

filename = "C:/Users/Sangamesh.sangamad/Dropbox/Thesis/Data Preparation/GenData.csv" 
with result_log = open(filename, 'w'): 
    # code writing to result_log 

오히려 수동 사이에 구분 기호로 문자열을 작성하는 것보다, 당신은 정말 csv module 사용해야합니다

import csv 

# .. 

column_names = (
    "Population_ID", "Product_Name", "Product_ID", "Year", 
    "Month", "Day", "Quantity_sold", "Sales_Price", "Discount", 
    "Actual_Sales_Price", tax) 

# .. 

with result_log = open(filename, 'wb'): 
    writer = csv.writer(result_log, delimiter=';') 
    writer.writerow(column_names) 

    # looping 
     row = [pop, product_name2, prod_id, year, month, quarter(month), day, 
       a[0], a[1], a[2], tax, a[3]] 
     writer.writerow(row) 
+0

좋은 아이디어 !! 감사 –

관련 문제