“Как обновить данные в файле CSV с помощью Python” Ответ

Python CSV

from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'my.csv'
tempfile = NamedTemporaryFile(mode='w', delete=False)

fields = ['ID', 'Name', 'Course', 'Year']

with open(filename, 'r') as csvfile, tempfile:
    reader = csv.DictReader(csvfile, fieldnames=fields)
    writer = csv.DictWriter(tempfile, fieldnames=fields)
    for row in reader:
        if row['ID'] == str(stud_ID):
            print('updating row', row['ID'])
            row['Name'], row['Course'], row['Year'] = stud_name, stud_course, stud_year
        row = {'ID': row['ID'], 'Name': row['Name'], 'Course': row['Course'], 'Year': row['Year']}
        writer.writerow(row)

shutil.move(tempfile.name, filename)
Tough Tuatara

Как обновить данные в файле CSV с помощью Python

# importing the pandas library
import pandas as pd
  
# reading the csv file
df = pd.read_csv("AllDetails.csv")
  
# updating the column value/data
# df is a file, loc is a code to finde element in csv file, inside of []: 5 is a row and
# 'Name' is a column
df.loc[5, 'Name'] = 'SHIV CHANDRA'
  
# writing into the file (rewrite csv file)
df.to_csv("AllDetails.csv", index=False)
  
print(df)

# so if in your csv file at row 5 and column 'Name' data was Kallem Kruthik now its 
# gonna be SHIV CHANDRA
Bored Buffalo

Ответы похожие на “Как обновить данные в файле CSV с помощью Python”

Вопросы похожие на “Как обновить данные в файле CSV с помощью Python”

Смотреть популярные ответы по языку

Смотреть другие языки программирования