简体   繁体   中英

Data not being written in csv

Im using the following code to populate csv

f = csv.writer(open("test.csv", "w"))

f.writerow(["user_id", "male", "female", "less15", "sixteen", "twentysix", 
            "thirtysix", "fortysixplus", "happy","neutral", "surprise"])


if __name__ == '__main__':

    with tf.Session() as sess:
        start_time = timeit.default_timer()

        x = json.loads(createjson(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))
        print(x)

        for row in x:
            print(row)
            f.writerow([row['user_id'], row['male'], row['female'], row['less15'], 
                        row['sixteen'], row['twentysix'], row['thirtysix'], 
                        row['fortysixplus'], row['happy'], row['neutral'], row['surprise']])

print(x) prints the following

[{'fortysixplus': 8, 'surprise': 11, 'female': 3, 'twentysix': 6,
'male': 2, 'user_id': 1, 'less15': 4, 'sixteen': 5, 'thirtysix': 7,
'neutral': 10, 'happy': 9}] {'fortysixplus': 8, 'surprise': 11,
'female': 3, 'twentysix': 6, 'male': 2, 'user_id': 1, 'less15': 4,
'sixteen': 5, 'thirtysix': 7, 'neutral': 10, 'happy': 9}

however the data is not being written in csv. why so?

UPDATE: I tried using dictwriter as follows,

if __name__ == '__main__':
    with tf.Session() as sess:

        start_time = timeit.default_timer()
        x = json.loads(createjson(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))


        for row in x:
            print(row)
            writer = csv.DictWriter(f = open('test.csv', 'w'), fieldnames=row.keys)
            # writer.writeheader()
            writer.writerow(row)

but still im getting the following error,

Traceback (most recent call last):
  File "C:/Users/R&D/Documents/Maxis_2/Maxis/src/dwell_time_maxis.py", line 128, in <module>
    writer.writerow(row)
  File "C:\Program Files\Anaconda3\lib\csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Program Files\Anaconda3\lib\csv.py", line 146, in _dict_to_list
    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
  File "C:\Program Files\Anaconda3\lib\csv.py", line 146, in <listcomp>
    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
TypeError: argument of type 'builtin_function_or_method' is not iterable

Here's a DictWriter example using your sample data and Python 3. Note the correct way to open a file for use with the csv module is to use the newline='' parameter. fieldnames is a required parameter when opening a DictWriter so the class instance knows what column names you want and in what order.

x is a list of dictionaries. writerows will write each dictionary as a line in the output file in one shot. You could also use for row in x: w.writerow(row) to write one line at a time.

x = [{'fortysixplus': 8, 'surprise': 11, 'female': 3, 'twentysix': 6,
      'male': 2, 'user_id': 1, 'less15': 4, 'sixteen': 5, 'thirtysix': 7,
      'neutral': 10, 'happy': 9}]

with open('test.csv','w',newline='') as f:
    w = csv.DictWriter(f,fieldnames='user_id male female less15 sixteen twentysix thirtysix fortysixplus happy neutral surprise'.split())
    w.writeheader()
    w.writerows(x)

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