0

I want to generate a log file in which I have to print two lists for about 50 input files. So, there are approximately 100 lists reported in the log file. I tried using pickle.dump, but it adds some strange characters in the beginning of each value. Also, it writes each value in a different line and the enclosing brackets are also not shown.

Here is a sample output from a test code.

import pickle
x=[1,2,3,4]
fp=open('log.csv','w')
pickle.dump(x,fp)
fp.close()

output:

enter image description here

I want my log file to report: list 1 is: [1,2,3,4]

Matthias
  • 4,481
  • 12
  • 45
  • 84
MAIGA
  • 27
  • 4
  • Does this answer your question? [Save a list to a .txt file](https://stackoverflow.com/questions/33686747/save-a-list-to-a-txt-file) – Georgy Oct 20 '20 at 20:56

3 Answers3

0

pickle is for storing objects in a form which you could use to recreate the original object. If all you want to do is create a log message, the builtin __str__ method is sufficient.

x = [1, 2, 3, 4]
with open('log.csv', 'w') as fp:
    print('list 1 is: {}'.format(x), file=fp)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

If you want your log file to be readable, you are approaching it the wrong way by using pickle which "implements binary protocols"--i.e. it is unreadable.

To get what you want, replace the line

pickle.dump(x,fp)

with

fp.write(' list 1 is: '
fp.write(str(x))

This requires minimal change in the rest of your code. However, good practice would change your code to a better style.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
  • Thanks for your response. After posting the question I could figure out the simple approach for using string by myself. However, it is always nice to know that the solution I thought of is acceptable by others as well. :) – MAIGA Aug 14 '18 at 19:19
0

Python's pickle is used to serialize objects, which is basically a way that an object and its hierarchy can be stored on your computer for use later.

If your goal is to write data to a csv, then read the csv file and output what you read inside of it, then read below.

Writing To A CSV File see here for a great tutorial if you need more info

import csv
list = [1,2,3,4]
myFile = open('yourFile.csv', 'w')
writer = csv.writer(myFile)
writer.writerow(list)

the function writerow() will write each element of an iterable (each element of the list in your case) to a column. You can run through each one of your lists and write it to its own row in this way. If you want to write multiple rows at once, check out the method writerows()

Your file will be automatically saved when you write.

Reading A CSV File

import csv
with open('example.csv', newline='') as File: 
reader = csv.reader(File)
for row in reader:
    print(row)

This will run through all the rows in your csv file and will print it to the console.