csv_file = request.FILES['file']
if not csv_file.name.endswith('.txt'):
messages.info(request,'This is not a csv file')
data_set = csv_file.read().decode('latin-1') #latin-1
io_string = io.StringIO(data_set)
next(io_string)
csv_reader = csv.reader(io_string, delimiter='\t',quotechar="|")
for column in csv_reader:
column_1 = str(column[1]).replace('\n','')
b = Module(
user= request.user,
a=column_1,
b=column[2],
)
b.save()
Here, in column_1
there is such data as an example in the .txt
file
This is
a value
and I want to output this data as
This is a value
after importing it, but I can't. How should I do?
CodePudding user response:
the csv reader iterates over rows, not columns. So if you want to append the data from a given column together, you must iterate over all the rows first. For example:
import csv
from io import StringIO
io_string = "this is , r0 c1\r\na value, r1 c2\r\n"
io_string = StringIO(io_string)
rows = csv.reader(io_string)
column_0_data = []
for row in rows:
column_0_data.append(row[0])
print("".join(column_0_data))
the rest of your code looks iffy to me, but that is off topic.
CodePudding user response:
I may not have explained it correctly. This is my fault I guess. The place where I put this code belongs to an import page.And here there is data in the data I want to import in .txt
format, but this data contains the \n
character.
if request.method == "POST":
txt_file = request.FILES['file']
if not txt_file .name.endswith('.txt'):
messages.info(request,'This is not a txt file')
data_set = csv_file.read().decode('latin-1')
io_string = io.StringIO(data_set)
next(io_string)
csv_reader = csv.reader(io_string, delimiter='\t',quotechar="|")
for column in csv_reader:
b = Module_Name(
user= request.user,
a = column[1],
b = column[2],
c = column[3],
d = column[4],
e = column[5],
f = column[6],
g = column[7],
h = column[8],
)
b.save()
messages.success(request,"Successfully Imported...")
return redirect("return:return_import")
This can be called the full version of my code. To explain, there is a \n character in the data that comes here as column[1]. This file is a .txt file from another export. And in this export column[1];
This is
a value
and my django localhost new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
gives a warning and aborts the import to the system.