Reputation: 121
infile = open('abc.csv', "r")
infile1 = open('xyz.csv', "r")
infile2 = open('pqr.csv', "r")
I am trying to read 3 csv files into infile, infile1, infile2. After that i have to pass them to a function. The problem is when i am trying to pass directly in, in1, in2 as arguments its showing
ValueError: invalid literal for int() with base 10:
convert_to(infile, infile1, infile2)
def convert_to(..,..,..)
How can i pass in, in1, in2 as arguments to the function definition and call? Is this the right way then why it is showing this error. Is there any other better and efficient way to do this?
Upvotes: 0
Views: 9494
Reputation: 417
Just an suggestion, why don't you use pandas
.
In case of pandas
it is very easy to pass them as object to functions and do whatever you want to do with it.
import pandas as pd
in1 = pd.read_csv('path/to/file1.csv')
in2 = pd.read_csv('path/to/file2.csv')
in3 = pd.read_csv('path/to/file3.csv')
def convert_to(*args):
for df in args:
print "hi"
convert_to(in1,in2,in3)
Let me know if pandas works for you.
in convert_to
are you trying to convert any value to integer
. It might be an issue in your case. Converting string
into integer
will throw the error that you have mentioned at the top.
here is an example:
print int('56.0000')
print float('56.0000')
you can observe,
ValueError: invalid literal for int() with base 10: '56.0000000'
for first case and for the second case,
56.0
I think that is the issue you are having.
Upvotes: 0
Reputation: 3001
First, you can't use in as a variable name since it's a reserved word in python:
import csv
file1 = open("abc.csv", "r")
file2 = open("xyz.csv", "r")
file3 = open("pqr.csv", "r")
def convert_to(a, b, c):
...
convert_to(file1, file2, file3)
Also, that's not the way I would do it since I would like to make sure the file is closed after it has been used. See this. I would create a function that accepts the filenames as arguments and then process the files inside the function:
import csv
filename1 = "abc.csv"
filename2 = "xyz.csv"
filename3 = "pqr.csv"
def convert_to(a, b, c):
with open(a, "r") as file1:
pass # do something with file abc.csv
with open(b, "r") as file1:
pass # do something with file xyz.csv
with open(c, "r") as file1:
pass # do something with file pqr.csv
convert_to(filename1, filename2, filename3)
Upvotes: 1
Reputation: 2129
import csv
csv_files = ['abc.csv','xyz.csv','abcd.csv']
def convert_to(files):
for file in files:
with open(file,'r') as f:
# Do something
You can pass the list of files to a function then made the changes/covert them as you wish.
Upvotes: 0
Reputation: 115
"in" is a keyword. You should change that variable name.
Not just the variable name... you need to change the parameters also.
i did it, and it worked fine for me.
import csv
in1 = open('abc.csv', "r")
in2 = open('xyz.csv', "r")
in3 = open('pqr.csv', "r")
def convert_to(in1, in2, in3):
return 'hi'
print(convert_to(in1,in2,in3))
Upvotes: 0