简体   繁体   中英

How can I make a csv file from a python module code?

NOTICE - this is not about making a csv file from a single csv file or excel files, but for a single python module application.

I am working on an assignment making a csv file from an Tic-Tac-Toe game, so I made some original Python module and main code that runs with the result's sub-data saved temporarily when I run the main code. (A-Module, B- Main code). Each information is temporarily stored in like 'self.xxx' under the structure self. The original python module and main code cannot be modified.

A-Module

class TTT_Env():
    def __init__(self):
        self.state = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
        self.done = False
        self.turn = 'X'
        self.winner = None

    def print_state(self):
        for row in self.state:
            print(*row)

    def step(self, r, c):
        if r not in [0, 1, 2] or c not in [0, 1, 2]:      
            print('Enter the number 0~2')
        elif self.state[r][c] != '_': 
            print('Put your mark on the blank position!')
        else:
            self.state[r][c] = self.turn

            tmp = self.state[0]+self.state[1]+self.state[2]   
            if tmp.count('_') == 0:
                self.done = True

            self._winner_check()

            self.turn = 'O' if self.turn == 'X' else 'X' 

    def reset(self):
        self.state = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
        self.done = False
        self.turn = 'X'
        self.winner = None

    def _winner_check(self):
        for row in self.state:
            if ''.join(row) == self.turn * 3:
                self.winner, self.done = self.turn, True

        for col in zip(*self.state): 
            if ''.join(col) == self.turn * 3:
                self.winner, self.done = self.turn, True

        diag_1 = self.state[0][0] + self.state[1][1] + self.state[2][2] 
        diag_2 = self.state[0][2] + self.state[1][1] + self.state[2][0]  
        if diag_1 == self.turn * 3 or diag_2 == self.turn * 3:      
            self.winner, self.done = self.turn, True

B- Main Code

from TTT_env import *
from game_logger import *

env = TTT_Env()

print("Game start")
history = []
env.print_state()
while not env.done:
    action = input("Player %s, enter your index of your mark(compared by space):"%env.turn)
    r, c = action.split(' ')
    history.append(env.turn, int(r), int(c), env.done, env.winner)
    env.step(int(r), int(c))
    env.print_state()

logging(history)
if env.winner == None:
    print("Draw.")
else:
    print("The winner is player %s!"%env.winner)

The target is here; (1) I have to make a.csv file, which contains the temporarily stored data-set of self.(The original program is still working though)

(2) I need to make a record on the csv file when original program has ended.

The code below is one of my prototype about the target, it has lots of mistake, I know, but please teach me a lot.

Thanks!

So when I got the right answer, I was astonished by knowing not to use the readlines function nor read nor readline function at all - here is the answer code

import csv
import os
import datetime

def logging(history):
    if not os.path.isdir("log"):
        os.mkdir("log")

    if not os.path.exists("log/play_log.csv"):
        with open("log/play_log.csv", "w") as f:
            writer = csv.writer(f, delimiter=',', quotechar='"')
            header = ["step", "player", "row", "column", "done", "winner"]
            writer.writerow(header)

    with open("log/play_log.csv", "a") as f:
        writer = csv.writer(f, delimiter=',', quotechar='"')
        for i, p_r_c_d_w in enumerate(history):
            s_p_r_c_d_w = [i+1] + p_r_c_d_w
            writer.writerow(s_p_r_c_d_w)
        writer.writerow([str(datetime.datetime.now())])

First I had to do was making a path directory by checking the os.path.isdir statement. If the directory is not stated, you have to make one with the os.mkdir statement.

Then, using a sub.csv file 'play_log.csv' I had to make a delimiter and quotechar of course- make a header to compare which is the progressing dataset afterwards. I have to write it down on the.csv file too.

The last part of this code represent we should make a space for dataset of the history logs - by distributing the history's data to the p_r_c_d_w, and also compares the latest record by making the step(i) working by manually adding 1 when the code is working.

And for number 2, we should make a writerow statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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