I want to check a CSV if it has a value that matches a variable. If it does contain that variable I want to print out 'variable present'
I tried to check each row for matching text of the variable and each field in the row. I do not get an error message but the result is always negative.
import csv
old_name = "random name already present in the table"
with open("data.csv", "r") as csv_file:
fieldnames = ["name", "price"]
csv_reader = csv.DictReader(csv_file, fieldnames=fieldnames)
for row in csv_reader:
for field in row:
if field == old_name:
print("already there")
else:
print("not there")
Output is just 'not there' for each item in the table.
Each row returned by iterating DictReader gives you a dict containing the column name as key, you should do something like:
for row in csv_reader:
if row['name'] == old_name
Related
I've been working this problem way too long, please explain to me why the header keeps repeating in my output csv.
I have an input csv with this data:
name,house
"Abbott, Hannah",Hufflepuff
"Bell, Katie",Gryffindor
"Bones, Susan",Hufflepuff
"Boot, Terry",Ravenclaw
The problem requires reversing last and first name, separate name into two columns, and make a new header with 3 columns for the output csv. Here's what I have:
while True:
try:
# open file
with open(sys.argv[1]) as file:
# make reader
reader = csv.reader(file)
# skip first line (header row)
next(reader)
# for each row
for row in reader:
# identify name
name = row[0]
# split at ,
name = name.split(", ")
# create var last and first, identify var house
last = name[0]
first = name[1]
house = row[1]
# writing the new csv
with open(sys.argv[2], "a") as after:
writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])
# HEADER ONLY NEEDS TO OCCUR ONCE
writer.writeheader()
writer.writerow({"first": first, "last": last, "house": house})
sys.exit(0)
my output csv:
first,last,house
Hannah,Abbott,Hufflepuff
first,last,house
Katie,Bell,Gryffindor
first,last,house
Susan,Bones,Hufflepuff
I've tried removing the while loop, unindenting and indenting, writing a row manually with the header names (which caused errors). Please help. Thanks!
You can add a variable that hold whether a header was printed or not, ex write_header
while True:
try:
write_header = True
# open file
with open(sys.argv[1]) as file:
# make reader
reader = csv.reader(file)
# skip first line (header row)
next(reader)
# for each row
for row in reader:
# identify name
name = row[0]
# split at ,
name = name.split(", ")
# create var last and first, identify var house
last = name[0]
first = name[1]
house = row[1]
# writing the new csv
with open(sys.argv[2], "a") as after:
writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])
# HEADER ONLY NEEDS TO OCCUR ONCE
if write_header:
writer.writeheader()
write_header = False
writer.writerow({"first": first, "last": last, "house": house})
sys.exit(0)
See how i used write_header
On an other note, you can refactor your code to open the csv writer before the for loop, write headers there, then write values as you do now without the need to reopen the file each time you want to write a row
#I get the name and the score variable from separate files, then I put them both in a CSV file line and then I cannot get them into the table because it says I only need two inputs (name, score)
GetName = open("namefile.txt")
PlayerName = GetName.read()
GetScore = open("scorefile.txt")
PlayerScore = GetScore.read()
print(PlayerScore)
print(PlayerName)
#This is how ScoreList should look like for the enumerate to take it ScoreList = [PlayerName,PlayerScore]
f=open("Score.csv", "a", newline="")
tup=(PlayerName,str(PlayerScore))
writer =csv.writer(f)
writer.writerow(tup)
f.close()
with open('Score.csv', 'r') as csv_file:
readCSV = csv.reader(csv_file, delimiter=',')
print(readCSV)
for row in readCSV:
#print(row)
ScoreList = row
for i, (name, score) in enumerate(ScoreList, start=1):
LeaderList.insert("", "end", values=(i, name, score))
With the help of Pandas you can easily do it
import pandas as pd
table = pd.read_csv('Score.csv')
I am trying to write data to a csv to a new field/column with if statements (based on values already present in the list). I have a list of UIDs (Field name Class):
ACRW,
AOC,
IFSE,
LN,
RLW,
etc,
This is what I have so far:
import csv
with open('PythonProject.csv', 'r') as rd_list:
csv_reader = csv.reader(rd_list)
with open ('new_rdlist.csv', 'w', newline='') as new_csvfile:
fieldnames = ['Class', 'Description', 'Flex']
csv_writer = csv.DictWriter (new_csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
csv_writer = csv.writer(new_csvfile)
Class = ''
for row in csv_reader:
if Class == 'C':
value = 'Cable'
elif Class == 'W':
value = 'Wave'
elif Class == 'RT':
value = 'Therm'
elif Class == 'H':
value = 'Heat'
else:
value = 'Unit'
csv_writer.writerow(row)
input('\nNew List is in your directory, Press Enter to exit')
Expected result is to have the csv populate to be,
Class, Description, Flex (which is the new field)
(ACRW, unique name, Unit)
(AOC, unique name, Unit)
(C, unique name, Cable)
(IFSE, unique name, Unit)
(LN, unique name, Unit)
(RLW, unique name, Unit)
(W, unique name, Wave)
etc...
I hope I understood you right, I assume you intend to read in the "PythonProject.csv" and write the same data with an additional column to "new_rdlist.csv".
Accessing & Manipulating the data
The main issue seems to be understanding rows in DictReader and DictWriter. As you are already using DictWriter I suggest using the DictReader class as well. The cells/fields in each row can be accessed by their column names. You can access the "Class" value that way, so the first check would read:
if row["Class"] == "C":
value = "Cable"
you can even directly manipulate the row dictionary:
if row["Class"] == "C":
row["Flex"] = "Cable"
After that modification the rest should be easy to solve!
Other issues
csv_writer = csv.writer(new_csvfile) is redundant as it overwrites the csv_writer variable again
(Almost) final code
import csv
with open('PythonProject.csv', 'r') as rd_list:
csv_reader = csv.DictReader(rd_list)
with open ('new_rdlist.csv', 'w', newline='') as new_csvfile:
fieldnames = ['Class', 'Description', 'Flex']
csv_writer = csv.DictWriter (new_csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
for row in csv_reader:
if row["Class"] == "C":
row["Flex"] = "Cable"
...
row["Flex"] = "Unit"
csv_writer.writerow(row)
input('\nNew List is in your directory, Press Enter to exit')
im trying to get the value of the first and the thirs row in a csv file.
my approach gives me the first and the 3rd character of the first row. instead of the fields in row 1 and 3. Would be great if someone could give me a tipp what im doing wrong!
lang_tags = []
tweets = []
#open and read csv file
with open("tweet-corpus.csv", "r") as csv_file:
reader = csv.DictReader(csv_file)
for row in csv_file:
lang_tags = row[0]
tweets = row[2]
for lan in lang_tags:
print("lang: ", lang_tags)
print("tweet: ", tweets)
Use the csv reader object.
Ex:
with open("tweet-corpus.csv", "r") as csv_file:
reader = csv.reader(csv_file)
for row in reader:
lang_tags = row[0]
or
with open("tweet-corpus.csv", "r") as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
lang_tags = row['YOURCOL_NAME']
tweets = row['YOURCOL_NAME']
If your data looks anything remotely like:
col_name0, col_name1, col_name2, ...
value0, value1, value2, ...
value0, value1, value2, ...
I recommend using pandas.
import pandas as pd # by convention, we always import pandas as pd
df = pd.read_csv(filename)
column = df[column_name]
I have the code:
def checkdetails(username, password):
with open('Data.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print(row)
if username == row[0]:
#This is where i will need to check if the password in the next column matches
This searches through the csv's first column in order to see if the username exists. It works.
What i need it to do next is move along to the next column in that row and if it matches the value
Just do:
if row[0] == username and row[1] == password: