0

Explanation: I need to take parameters from file1 and need to use in some function and then i need to take results from that function then need to write these test_name and results to a new csv i.e file2. while iam doing with below example iam getting some errors.

Readind from a CSV file1 and writing to a new CSV file2 using python

with open(inputs.csv, 'rb') as file1:  #Need to read params from this file
    data = list(csv.reader(file1))
with open('output.csv', 'wb') as file2: #Need to write results to this file
    writer = csv.writer(file2)
for row in data:
    api = row[0]
    test_name =row[1]
    out = funtion_call(api, test_name)
    writer.writerow([test_name, out])
file1.close()
file2.close()

Output:

 writer.writerow([test_name, out])
ValueError: I/O operation on closed file
5
  • Please paste the exact error message and traceback in your question, "some errors" is not a very useful information! Commented Jun 23, 2017 at 9:50
  • just use pandas Commented Jun 23, 2017 at 9:54
  • 2
    Installing pandas just for the sake of reading a csv file is overkill... Commented Jun 23, 2017 at 9:55
  • 1
    with open(inputs.csv, 'rb') as file1: Maybe this should be: with open('inputs.csv', 'r') as file1:. Also why 'rb' and 'wb'? You are reading a glorified text file. Not a bytes files. Commented Jun 23, 2017 at 10:00
  • hi @selten98, when iam using a single file only for read from csv i.e file1 its worked fine with 'rb'. any way i tried with your suggession as well but same error Commented Jun 23, 2017 at 10:05

1 Answer 1

1

If you are using the with statment, your operations need to be within that block, with handles the opening and closing for you.

with open(inputs.csv, 'rb') as file1:  
    data = list(csv.reader(file1))
    with open('output.csv', 'wb') as file2: 
        writer = csv.writer(file2)
        for row in data:
        api = row[0]
        test_name =row[1]
        out = funtion_call(api, test_name)
        writer.writerow([test_name, out])

Without all your code, it is impossible to test this, but hopefully you get the idea. This link might help too: http://effbot.org/zone/python-with-statement.htm

Sign up to request clarification or add additional context in comments.

2 Comments

true, but with open(inputs.csv, 'rb') as file1, open('output.csv', 'wb') as file2 seems much more readable - especially because there is one level of indentation fewer...
@hiroprotagonist, I agree, that would be a more readable solution and would work better if there are a lot of operations on the two files.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.