This is the function which make an attempt to update the content:
def write_csv(self, file_path, fields, rows):
with open(file_path, 'wb') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames=fields)
writer.writerow(dict(zip(fields, fields)))
for row in rows:
writer.writerow(row)
The error which I'm getting is as follows:
C:\sample_data_set.csv
Initial Records : 19
Removed : 3
Traceback (most recent call last):
File "C:/Python_project/amit_test.py", line 79, in <module>
v.main()
File "C:/Python_project/amit_test.py", line 73, in main
self.write_csv('output/{0}'.format(os.path.basename(file_path)), fields, rows)
File "C:/Python_project/amit_test.py", line 41, in write_csv
with open(file_path, 'wb') as csvFile:
IOError: [Errno 2] No such file or directory: 'output/sample_data_set.csv'
I have checked that the path of sample_data_set.csv correct and does exist.
Complete code is available here https://gist.github.com/shashank136/f5557a1d0a42d1ae615a6e4c12b21ff7
file_path
maybe
file_path = r"C:\Python_project\output\sample_data_set.csv"
you can try!
Depends on your file_path, notes that it doesn't automatically create the intermediate directories when you opening a file
import os
def write_csv(self, file_path, fields, rows):
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'wb') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames=fields)
writer.writerow(dict(zip(fields, fields)))
for row in rows:
writer.writerow(row)
Related
Right now my nmap csv is putting semicolons in the file which I need to change to commas.
nmap scan
import first
import csv
import nmap
csvFilePath = "nmapscan1.csv"
ipAddress = first.ipAddress
port = first.port
#nmap scan using user input varibles
nm = nmap.PortScanner()
nm.scan(ipAddress,port)
csv = nm.csv()
print(csv)
#writing to csv file
with open(csvFilePath, "w") as csvFile:
csvFile.write(csv)
#changes ; to , for database use
with open(r"nmapscan1.csv") as in_file, open(r"nmapscan.csv", 'w') as
out_file:
semicolonin = csv.reader(in_file, delimiter=';')
commaout = csv.writer(out_file, delimiter=',')
for row in semicolonin:
commaout.writerow(row)
error I get in Ubuntu terminal
Traceback (most recent call last):
File "second.py", line 23, in <module>
semicolonin = csv.reader(in_file, delimiter=';')
AttributeError: '_io.TextIOWrapper' object has no attribute 'reader'
Set a different name to csv on csv = nm.csv(). It is overwriting your csv on import csv.
Edited*
This part:
csv_data = nm.csv()
print(csv_data)
#writing to csv file
with open(csvFilePath, "w") as csvFile:
csvFile.write(csv_data)
This code shows the error in the title.. Help me out plz.I wrote the following code to write to a csv file reading the input from another file but this shows the error.When i change "r" to "rb" then it shows "iterator should return byte" error.
error->Traceback (most recent call last):
File "C:/Users/abhirav.sati/Downloads/salesdata.py", line 34, in
csv_reader(csvReader,path)
File "C:/Users/abhirav.sati/Downloads/salesdata.py", line 11, in csv_reader
for row in read:
_csv.Error: iterator should return strings, not list (did you open the file in text mode?)
import csv
def csv_reader(fileobj,path):
read=csv.reader(fileobj,delimiter=',')
with open(path, "wt") as csv_file:
write=csv.writer(csv_file, delimiter=',')
i=1
for row in read:
if(i==1):
write.writerow(",".join(row))
i=2
continue
if(row[3]=="Trade"):
continue
else:
if(row[6]==NULL):
r=[row[0],row[0],"A,",row[8],row[9],row[0]]
#r=row[0]+row[0]+"A,"+row[8]+row[9]+row[0]
write.writerow(r)
else:
r=[row[0],row[0],"B,",row[6],row[7],row[0]]
#r=row[0]+row[0]+"A,"+row[8]+row[9]+row[0]
write.writerow(r)
if __name__ == "__main__":
path="sales.csv"
csv_path = "FlowEdge-TRTH-Time_Sales.csv"
f_obj = open(csv_path, "r")
data=csv.reader((line.replace('\0','') for line in f_obj), delimiter=",")
csv_reader(data,path)
Your code is applying csv.reader on another csv.reader object. Look carefully at your __main__ and csv_reader function to make sure you understand why this is the case.
A better solution is to use with open... with multiple files:
with open(path, 'wt') as f1, open('csv_path', 'r') as f2:
write = csv.writer(f1, delimiter=',')
read = csv.reader(f2, delimiter=',')
I am new to Python programming and recently I am trying to read a csv file and then save the data from that csv file to a text file. This is the code I am using
csv_file = open('example.csv', 'r')
txt_file = open('example.txt', 'w')
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
[my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
my_output_file.close()
I am getting this error
File "c:\Users\Desktop\Folder\tokenizing.py", line 41, in <module>
with open(txt_file, 'w') as my_output_file:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Does anyone knows why is it complaining?
Pass the filenames to the open calls and use a for loop not a list comp and let the with context managers of the file objects take care of closing the files:
csv_file = 'example.csv'
txt_file = 'example.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
for row in csv.reader(my_input_file):
my_output_file.write(" ".join(row)+'\n')
when i'm trying to make a copy from csv file to edit it away of the original
then I apply the effects to the original
import csv
import shutil
from tempfile import NamedTemporaryFile
filename = "data1.csv"
temp_file = NamedTemporaryFile(delete=False)
print(temp_file.name)
with open(filename, "r",encoding='utf8') as csvfile, temp_file:
reader = csv.DictReader(csvfile)
fieldnames = ["id", "name", "email", "sent"]
writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
# writer.writeheader()
for row in reader:
writer.writerow({
"id":row["id"],
"name":row["name"],
"email":row["email"],
"sent":""
})
I get this error :/
C:\Users\Arafat\AppData\Local\Temp\tmpwgkcslas
Traceback (most recent call last):
File "C:\Users\Arafat\Desktop\30dpython\hungry_data.py", line 49, in <module>
"sent":""
File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Users\Arafat\AppData\Local\Programs\Python\Python36-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
The error is the result of your temp_file being opened in binary mode rather than text mode (the default is w+b). Change it to:
temp_file = NamedTemporaryFile(mode='w', encoding='utf8', delete=False)
(the encoding is not strictly necessary, but since you're specifying it on the input, makes sense to specify it on the output).
See https://docs.python.org/3/library/tempfile.html
I have a txt file and I want to save each line as a list in a new file with fname as the new file name. But the output is not being saved. What am I missing?
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
out.write(line)
i +=1
To do what you want, you need to fix two things, one is to open the output files in "append" mode so their previous contents aren't wiped-out everytime something additional is written to them.
Secondly you need some way to know the raw data from the file for each csv row it reads. This can be difficult when you use an extension like the csv module and don't know the internals (which you shouldn't use anyway).
To work around that in this case, you can pass a custom csvfile argument to the csv.reader that will give you the information needed. Basically a small preprocessor of the data being read. Here's what I mean:
import csv
def pre_reader(file):
"""Generator that remembers last line read."""
for line in file:
pre_reader.lastline = line
yield line
with open('test_gen.csv', 'rU') as csvfile:
reader = csv.reader(pre_reader(csvfile), delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'a') as out:
out.write(pre_reader.lastline)
i +=1
Change:
with open(fname, 'w') as out:
out.write(line)
To:
with open(fname, 'a') as out:
out.write(line)
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
Better way:
import csv
with open('file.txt', 'rU') as csvfile, open(fname, 'w') as out:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
out.write(line)
You cannot write a list so change penultimate line to **out.write(str(line))**
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
------> out.write(str(line))
i +=1