Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read value from a CSV
#1
Ciao,

I'm basically new with python. I have a CSV like the one one attached and I want save each column (without the ";") into a variable.
I need a while loop.
Until now I've understood only how to open the CSV and in case make a print of it

with open('C:\python\csv_prova.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=';')
   
    for i in csv_reader:
        for j in i:
           print(j, end=" ") 
     print("")
but with the loop and how to get the single value I'm a bit lost. can you help me? thanks

Attached Files

.csv   csv_prova.csv (Size: 189 bytes / Downloads: 117)
Reply
#2
If you want to read a specific cell you can use pandas,

example reads cell in row 2 column 0

import pandas as pd

df = pd.read_csv('csv_prova.csv', delimiter=';')

print(df.iat[2,0])
martinmistere likes this post
Reply
#3
Remember, csv files are just text files. Often, using mycsvfile.readlines() will get you a list you can manipulate.

Here some basic open and close csv stuff.

import csv
import glob

path = '/home/pedro/myPython/csv/'
csvs = glob.glob(path + '*.csv')
for file in csvs:
    print('The csv files are:', file)

myfile = input('Copy and paste the whole path to the file you want here ... ')

# csv_reader is gone after you use it one time
# it is convenient to copy the data to a list

with open(myfile) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    data = []
    for row in csv_reader:
        data.append(row)

for d in data:
    print(d)
    # get the third element in each row
    print('Third element is', d[2])
    for l in range(len(d)):
        # show all elements of each row
        print(d[l])

# add something to each row
for i in range(len(data)):
    data[i].append('X')
    
# an empty string
output = ''
for d in data:
    string = ';'.join(d) + '\n'
    output = output + string

name = myfile.split('.') 
newname = name[0] + '_modified_csv.csv'

with open(newname, 'w') as nf:
        nf.write(output)

with open(newname) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=';')
    for row in csv_reader:
        print(row)
martinmistere likes this post
Reply
#4
thank you both for the reply and support.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020