I am pretty new with python and I cannot shake this "index out of range error" at line wks.insert_row([row[1],row[2],row[3]], 1). I am trying to send the data to google sheets but it is not working. The wks.insert_row([1,2,3],1) does send 1,2, and 3 to the sheet. It must be something with row[1], row[2], row[3]. I have tried removing wks.insert_row([1,2,3],1) and changing the index to random numbers, still does not work. Thank you for the help!
import csv
import gspread
import time
MONTH = 'July'
file = f"Chase_{MONTH}.csv"
transactions = []
def ChaseFin(file):
with open(file, mode = 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
date = row[1]
name = row[2]
amount = row[3]
transaction = ((date, name, amount))
print(transaction)
transactions.append(transaction)
return transactions
sa = gspread.service_account()
sh = sa.open("Personal Finances")
wks = sh.worksheet(f"{MONTH}")
rows = ChaseFin(file)
for row in rows:
wks.insert_row([row[1],row[2],row[3]], 1)
time.sleep(2)
wks.insert_row([1,2,3],1)
Related
I have a csv file that looks like this:
Current csv file
Would like make a new csv file that looks like this:
Desired csv file
My first thoughts are to:
r1= []
r2 = []
with open('loadba1.csv', "r") as csv_file:
data = csv.reader(csv_file, delimiter=',')
f or rows in data:
r1.append(rows[0])
r2.append(rows[1])
r1 will give - TRUE
r2 will give - 'L_602356450160818331', 'wan1'
Then loop through again r2 to pull out each value and 'somehow' combine.
I also cannot loose the value relationship e.g. TRUE - wan1 - L_602356450160818331
I am not sure of the approach I should take. Please advise.
What you probably want to do is use a manual while loop rather than for:
with open('loadba1.csv', "r") as csv_file:
data = csv.reader(csv_file, delimiter=',')
while True:
try:
load_bal, interface = next(data)
except StopIteration:
break # end of file
try:
_, the_id = next(data)
except StopIteration:
raise ValueError("No ID row for %s" % interface)
... # write out (load_bal, interface, the_id)
import pandas as pd
df = pd.Dataframe("csv1.csv", index = False)
result = []
Id, LoadBal, Interface = "","",""
for index, row in df.iterrows():
for col, val in row.iteritems():
if col == 0 and val:
LoadBal = val
elif LoadBal:
Interface = val
result.append({"LoadBal": LoadBal, "Interface": Interface,"Id": Id })
Id, LoadBal, Interface = "","",""
elif col!=0:
Id = val
result = pd.DataFrame(result)
result.to_csv("csv2.csv")
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 need to scan through line by line in time column time in CSV file, and see if there was activity in another column during 5 hours ago, then add column with value 1.
Here is my idea:
import csv
from collections import namedtuple
from contextlib import closing
light3 = pd.read_csv('G:/light3.csv')
light3.Time = pd.to_datetime(light3.Time)
m = light3.Time - DateOffset(hours = 5)
def search():
item = light3[(light3['Time']> m)| (light3['Time']== m)]
raw_data = 'G:/light3.csv'
failure = 'No matching item could be found with that item code. Please try again.'
check = False
with open('G:/project/test.pcap_z/light.csv','r') as csvinput:
with open('G:/light1.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator='\n')
reader = csv.reader(csvinput)
read_data = csv.DictReader(csvinput, delimiter=';')
item_data = namedtuple(read_data['Time'], read_data.Time)
all = [ ]
row = next(reader)
row.append('f')
all.append(row)
while check == False:
for row in reader:
if row.Item == item:
row.append('f')
all.append(row)
row.append(1)
writer.writerows(all)
I'm using this information (downloaded the file to my computer) http://www.genome.gov/admin/gwascatalog.txt
and wrote this
import csv
path = '/Users/mtchavez/Documents/ALS/Diseasome/GWAS.txt'
read_file = open(path)
reader = csv.reader(read_file, delimiter = '\t')
fieldnames = reader.next()
rows = list(reader)
read_file.close()
write_file = open('datatest.csv', 'wb')
writer = csv.writer(write_file, delimiter = '\t')
writer.writerow(('disease', 'genes'))
disease_gene = dict()
for row in rows:
disease = row[7]
reported_genes = row[13]
but I get an error message:
File "data1.py", line 18, in <module>
disease = row[7]
IndexError: list index out of range
There is an empty line at the end of this csv file and it will create an empty row. Delete the last line and the code works fine.
Try filtering for empty lines:
for row in rows:
if not row: continue
disease = row[7]
reported_genes = row[13]
Or more specifically, filter for the desired length:
for row in rows:
if len(row) != EXPECTED_LENGTH_OF_RECORD: continue
disease = row[7]
reported_genes = row[13]
I'm trying to add a new column by copying col#3 and then append #hotmail to the new column
Here is the script, only problem is that it will not finish processing the input file, it only show 61409 rows in the output file, whereas in the input file there are 61438 rows.
Also, there is an error message (the input file does not have empty line at the end):
email = row[3]
IndexError: list index out of range
inFile = 'c:\\Python27\\scripts\\intake.csv'
outFile = 'c:\\Python27\\scripts\\final.csv'
with open(inFile, 'rb') as fp_in1, open(outFile, 'wb') as fp_out1:
writer = csv.writer(fp_out1, delimiter=",")
reader = csv.reader(fp_in1, delimiter=",")
for col in reader:
del col[6:]
writer.writerow(col)
headers = next(reader)
writer.writerow(headers + ['email2'])
for row in reader:
if len(row) > 3:
email = email.split('#', 1)[0] + '#hotmail.com'
writer.writerow(row + [email])
It looks like you edited the code you received in your earlier answer.
Change
email = email.split('#', 1)[0] + '#hotmail.com'
to
email = row[3].split('#', 1)[0] + '#hotmail.com'