O
O
onekrugoikov2020-06-03 23:45:17
Python
onekrugoikov, 2020-06-03 23:45:17

How to replace csv column data?

I need a script that opens a simple.csv file , selects the images cell (where the links are) and removes all characters after the ? in each column.

Here is an example, but it does not know how to write changed data to the old file:

import csv

with open('simple.csv', 'r') as f:
    incl_col = [28]
    new_csv = []
    reader = csv.reader(f, delimiter=";")

    for row in reader:
        col = str(list(row[i] for i in incl_col))
        col = col.split('?')[0]
        print(col)
        new_csv.append(col)


How it was: https://habr.com/python?Test
How it should be: https://habr.com/python

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-04
@LazyTalent

one.

>>> import pandas as pd
>>> df = pd.read_csv('sample.csv')
>>> df
   id                        images
0   0   https://image.png?width=640
1   1  https://image2.png?width=640
2   2  https://image3.png?width=640
>>> df['images'] = df['images'].str.split('?').str[0]
>>> df
   id              images
0   0   https://image.png
1   1  https://image2.png
2   2  https://image3.png

2.
import csv
>>> with open('sample.csv', 'r') as f:
...     rows = list(csv.DictReader(f))
... 
>>> rows
[OrderedDict([('id', '0'), ('images', 'https://image.png?width=640')]), OrderedDict([('id', '1'), ('images', 'https://image2.png?width=640')]), OrderedDict([('id', '2'), ('images', 'https://image3.png?width=640')])]
>>> rows = [{k: v.split('?')[0] if k=='images' else v for k, v in row.items()} for row in rows]
>>> rows
[{'id': '0', 'images': 'https://image.png'}, {'id': '1', 'images': 'https://image2.png'}, {'id': '2', 'images': 'https://image3.png'}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question