Why my hardcoded data is not writing to a file? - python

def write_to_csv():
newRow = ['P12467','Cat','Ancora','Yes','Yes','D123456','Lost','14/09/2019','30/09/2019','return to owner',"290 Oak Avenue, BS79 8TR"]
//with open('DADSA 2019-20 CWK A DATA PETS.csv', 'wb') as csv_file:
with open("DADSA 2019-20 CWK A DATA PETS.csv", mode="a", newline='') as csv_file:
# reader = csv.reader(csv_file)
writer = csv.writer(csv_file)
for row in csv.reader(csv_file):
if row[0] == newRow[0]:
writer.writerow(newRow)
I am getting this error "for row in csv.reader(csv_file):
io.UnsupportedOperation: not readable" I dont really understand it what it means.

You have a typo, you should use newRow, not csvFile, fixed code below:
def write_to_csv():
newRow = ['P12467','Cat','Ancora','Yes','Yes','D123456','Lost','14/09/2019','30/09/2019','return to owner',"290 Oak Avenue, BS79 8TR"]
#with open('DADSA 2019-20 CWK A DATA PETS.csv', 'wb') as csv_file:
with open("DADSA 2019-20 CWK A DATA PETS.csv", mode="a", newline='') as csv_file:
# reader = csv.reader(csv_file)
writer = csv.writer(csv_file)
for row in csv.reader(newRow):
if row[0] == newRow[0]:
writer.writerow(newRow)

You can't read from a file opened in a mode. That's for appending to the file. You could use a+ mode, but you'll need to seek to the beginning of the file first.
But if you only want to add a new row, you don't need to read from the file first. Just open the file and write the new row.
def write_to_csv():
newRow = ['P12467','Cat','Ancora','Yes','Yes','D123456','Lost','14/09/2019','30/09/2019','return to owner',"290 Oak Avenue, BS79 8TR"]
with open("DADSA 2019-20 CWK A DATA PETS.csv", mode="a", newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(newRow)

Related

How to rewrite only one field (line[n]) in csv but in same time be able to work with data?

I have a csv file with three lines and three columns here.
This is the csv file
At first I want to print all the lines.
Subsequently, for each of them, program check whether it is written in the second field(index 1) USA. If so, program will take the price from the third field and multiply it by two.
Now I need to rewrite this doubled price instead of 2000 (in line with the USA)
import csv
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
writer = csv.writer(source)
for line in reader:
print(*line, sep=';')
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
Someone has already advised me to use the creation of a new file.
But this causes problems when I want to work with the data in the file first.
import csv
import os
with open('countries.csv', mode='r') as oldfile, open(
'countries.tmp', mode='w', newline='') as newfile:
# define a reader and a writer
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for line in reader:
print(*line, sep=';')
# copy everything changing the third field
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
for row in reader:
writer.writerow([row[0], row[1], ,new_price])
# ok, time to rename the file
os.replace('countries.tmp', 'countries.csv')
Thank you for answer
You are changing new_price at every iteration of your for loop. You should therefore be writing the row within the loop where you change the value:
with open('countries.csv', mode='r') as oldfile, open('countries.tmp', mode='w', newline='') as newfile:
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in reader:
price = int(row[2])
if row[1] == "USA":
price = price*2
writer.writerow([row[0], row[1], price])
os.replace('countries.tmp', 'countries.csv')

CSV created with Python is blank

This question was answered/resolved in the comments section.
I am a noob to Python and I wrote the code below thinking it would copy all the rows with "NY" as the state in the state field/column to a new csv file called "Output.csv".
import csv
f = open(r'C:\Users..\input.csv', 'r')
reader = csv.DictReader(f, delimiter=',')
output = open("C:...\Output.csv",'w')
fieldnames = ['firstScan', 'FinalScan', 'City', 'State', 'cld', 'daydiff']
writer = csv.DictWriter(output, fieldnames=fieldnames, delimiter=',')
for row in reader:
if row['State'] == 'NY':
writer.writerow(row)
Everything runs fine but the output csv is completely blank. The first tab is named "Output" but the sheet is blank. If I have it output to txt, that is blank as well. Any suggestions?
Try this instead:
import csv
with open('C:/Users/felasniper/Desktop/input.csv') as f:
reader = csv.DictReader(f, delimiter=',')
output = open("C:/Users/felasniper/Desktop/Output.csv", 'w')
fieldnames = ['firstScan', 'FinalScan', 'City', 'State', 'cld', 'daydiff']
writer = csv.DictWriter(output, fieldnames=fieldnames, delimiter=',')
for row in reader:
if row['State'] == 'NY':
writer.writerow(row)

Writing and reading to a csv file - I/O operation error

I need to create a file and write its header contents before the for loop. If I do it inside the loop, header content repeats for every iteration of the loop. When I execute the below code, I get the error "I/O operation on a closed file".
Is wondering there a work around for this issue? Any suggestions would be appreciated. TIA !!
csv_filename = "testfile4.csv"
with open(csv_filename, "wt") as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
# CSV Header
header = ["Post ID", "Permalink", "Create Time"]
writer.writerow(header)
for group in getGroups():
feed = getValues(group["id"], group["name"])
with open(csv_filename, "a") as csvfile:
for item in feed:
row = [item["id"], item["permalink_url"], item["created_time"]]
writer.writerow(row)
You could process all necessary operations in single with statement
csv_filename = "testfile4.csv"
with open(csv_filename, "wt") as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
header = ["Post ID", "Permalink", "Create Time"]
writer.writerow(header)
for group in getGroups():
feed = getValues(group["id"], group["name"])
for item in feed:
row = [item["id"], item["permalink_url"], item["created_time"]]
writer.writerow(row)

Cut data from one sheet into another in csv in python

I am working on a simple program to open a file and read certain rows and then print them in another new file but I want to cut them and remove them from the earlier csv. how do I do that?. This is what I have tried.
import csv
f = open('1.csv')
csv_f = csv.reader(f)
content_value = []
for row in csv_f:
if 'yepme' in row[2]:
content_value.append(row)
g = open('output.csv', 'wb')
wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)
I am editing and found the answer:
import csv
f = open('1.csv')
csv_f = csv.reader(f)
content_value = []
old_value = []
for row in csv_f:
if 'yepme' in row[2]:
content_value.append(row)
else:
old_value.append(row)
g = open('output.csv', 'wb')
wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)
h = open('2.csv','wb')
ws = csv.writer(h, dialect='excel')
ws.writerows(old_value)
A similar problem is mentioned in this question.
Short solution: Write two files: One with the extracted lines, one with the leftovers.
Coded solution:
import csv
with open('1.csv', 'r') as f:
csv_f = csv.reader(f)
new_content = []
old_content = []
for row in csv_f:
if 'yepme' in row[2]:
new_content.append(row)
else:
old_content.append(row)
with open('output.csv', 'wb') as f:
wr = csv.writer(f, dialect='excel')
wr.writerows(new_content)
with open('1.csv', 'wb') as f:
wr = csv.writer(f, dialect='excel')
f.writerows(old_content)
I never used csv, but you should get the idea. If your csv-file is very huge, you should probably read and write line-by-line to avoid memory issues.

Taking data from text file and writing it as a .csv file in python

EDIT: Thanks for the answers guys, got what I needed!!
Basically I am trying to take what I have stored in my textfile and I am trying to write that into a .csv file. In my file are tweets that I have stored and I am trying to have one tweet in each cell in my .csv file.
Right now it is only taking one tweet and creating a .csv file with it and I need it to take all of them. Any help is greatly appreciated. Here is what I have so far.
with open('reddit.txt', 'rb') as f:
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
for row in reader:
print row
cr = csv.writer(open('reddit.csv', 'wb'))
cr.writerow(row)
You'll need to create the writer outside of the loop:
with open('reddit.txt', 'rb') as input_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
with open('reddit.csv', 'wb') as output_file:
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
Although here it might be cleaner to open the files without with:
input_file = open('reddit.txt', 'rb')
output_file = open('reddit.csv', 'wb')
reader = csv.reader(input_file, delimiter=':', quoting=csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
input_file.close()
output_file.close()
Or you can still use with and just have a really long line:
with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
The line cr = csv.writer(open('reddit.csv', 'wb')) is inside the for loop. You need to open the file just once, place this line after
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
Then write to it as you did in each loop iteration.

Categories

Resources