gboyn
gboyn

Reputation: 71

Python: Removing specific char while writing in .csv file

I need to write a dictionary with lists as values into a CSV. Input looks like:

d = {'a': [1.11, 2.22, 3.33],
     'b': [4.44, 5.55, 6.66],
     'c': [7.77, 8.88, 9.99]}

The output should look like:

a    1.11    2.22    3.33
b    4.44    5.55    6.66
c    7.77    8.88    9.99

My code is

with open('Test.csv', 'w') as f:
    for key in d.keys():
        f.write("%s,%s\n"%(key,d[key]))

Which outputs:

a    [1.11    2.22    3.33]
b    [4.44    5.55    6.66]
c    [7.77    8.88    9.99]

How can I amend my code to remove the brackets upon storing into the csv file? I know I can go through the file later and remove the brackets but I would like to do it before or while I'm writing to it.

Upvotes: 2

Views: 412

Answers (4)

Glenn Mackintosh
Glenn Mackintosh

Reputation: 2779

Try:

for key, values in d.items():
    f.write("%s %s\n"%(key, " ".join([str(v) for v in values])))

You can't just join() the d[key] because they are numbers and have to be converted to strings.

However I do not really think that you want it to be space separated as you have shown since you said you wanted a CSV. If you want it comma separated, then it would be:

for key, values in d.items():
    f.write("%s, %s\n"%(key, ", ".join([str(v) for v in values])))

[edit]

I should clarify why you were getting the '[' and ']' in your original code.

In your code, the contents of d[key] is a list. When you tell python to print a list, it prints the elements of the list separated by commas and wrapped with opening and closing square brackets to show that the thing being printed is a list.

The answer avoids that by breaking up the list using the

for v in values

and then putting them back together with the join().

Upvotes: 4

isFibonacci
isFibonacci

Reputation: 41

Here is the code that I try to remove specific char in a dataframe column.

FILE_PATH = "***.csv"
DONE_PATH = "done.csv"
SPECIFIC_COL = "SPECIFIC_COL"
REMOVE_CHAR = 'Â'

df = pd.read_csv(FILE_PATH,encoding='utf-8')
df[SPECIFIC_COL] = df[SPECIFIC_COL].str.replace(,'')

# Before writing to the csv, check if it exists or not
try: 
    os.remove(DONE_PATH)
except OSError:
    pass

df.to_csv(DONE_PATH)

Upvotes: 0

Donka
Donka

Reputation: 48

I ran your code, the result is:

a,[1, 2, 3]
b,[4, 5, 6]
c,[7, 8, 9]

So, this is not the cleanest way, but it works:

with open('Test.csv', 'w') as f:
    for key in d.keys():
        f.write("%s"%(key))
        for k in d[key]:
            f.write(" %s"""%k)
        f.write("\n")
a 1 2 3
b 4 5 6
c 7 8 9

Upvotes: 0

Benjam
Benjam

Reputation: 1758

d[key] is a list that you can join with a space character to get the string you want:

f.write("%s,%s\n"%(key, " ".join(d[key])))

By the way, if you intend to do CSV, have a look at the standard module: https://docs.python.org/3/library/csv.html

Upvotes: 2

Related Questions