Python csv file tokenizing - python

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')

Related

Copy csv values to another csv

I'm copying the contents of a csv file and writing these to another so I can modify it later but can't figure out what the simple solution is. I thought I could keep the input csv_file and output writer files open while copying the contents, don't know if that's a good idea. My code
import csv, os
file_path = 'path/to/file.csv'
output_path = os.path.dirname(os.path.abspath(file_path)) + '/'
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
with open(output_path + 'results.csv', 'w', newline='') as writer:
for line in data_source:
writer.writerow(line)
This is the error I get:
AttributeError: '_io.TextIOWrapper' object has no attribute 'writerow'
The object that you think is the writer is not. Instead, you should construct the writer separately.
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
with open(output_path + 'results.csv', 'w', newline='') as results_file:
data_sink = csv.writer(results_file) #This is the important line
for line in data_source:
data_sink.writerow(line)
Can you try this code and see if this works?
import csv, os
file_path = 'path/to/file.csv'
output_path = os.path.dirname(os.path.abspath(file_path)) + '/'
with open(file_path) as csv_file:
data_source = csv.reader(csv_file, delimiter=',')
f = open(output_path + 'results.csv', 'w', newline='')
with f:
writer = csv.writer(f)
for line in data_source:
writer.writerow(line)
The error means that there is no method for writerow for the writer.

Iterator should return strings, not list error with csv.reader

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=',')

CSV file to list of lines?

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

How can I read individual lines from a CSV file?

At the moment I've got this function:
def writer(file_name)
open_file = open(file_name,"r+", newline='')
csv_output = csv.writer(open_file)
csv_output.writerow(student)
open_file.close()
where student is:
"string_1","string_2",int
I'm looking to read through the file first and check if the "string_1" that I'm writing matches any of the "string_1"s already written, but I can't find a built-in function that lets me read each line and store it as a list.
First, you have to open the file for reading, go through the file line by line and return, if "string_1" is found:
def append_student(file_name, student)
with open(file_name, "r") as f:
for line in csv.reader(f):
if line[0] == student[0]:
return
with open(file_name, "a") as f:
csv.writer(f).writerow(student)

Use Python to write on specific columns in csv file

I have data in a file and I need to write it to CSV file in specific column. The data in file is like this:
002100
002077
002147
My code is this:
import csv
f = open ("file.txt","r")
with open("watout.csv", "w") as output:
for line in f :
c.writerows(line)
It is always writes on the first column. How could I resolve this?
Thanks.
This is how I solved the problem
f1 = open ("inFile","r") # open input file for reading
with open('out.csv', 'w',newline="") as f:up # output csv file
writer = csv.writer(f)
with open('in.csv','r') as csvfile: # input csv file
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row[7] = f1.readline() # edit the 8th column
writer.writerow(row)
f1.close()
python 2 users replace
with open('out.csv', 'w',newline="") as f:
by
with open('out.csv', 'wb') as f:

Categories

Resources