Gra*_*ntU 117 python csv django
以下代码一直有效,直到今天我从Windows机器导入并出现此错误:
在未引用字段中看到的换行符 - 您是否需要以通用换行模式打开文件?
import csv
class CSV:
def __init__(self, file=None):
self.file = file
def read_file(self):
data = []
file_read = csv.reader(self.file)
for row in file_read:
data.append(row)
return data
def get_row_count(self):
return len(self.read_file())
def get_column_count(self):
new_data = self.read_file()
return len(new_data[0])
def get_data(self, rows=1):
data = self.read_file()
return data[:rows]
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
def upload_configurator(request, id=None):
"""
A view that allows the user to configurator the uploaded CSV.
"""
upload = Upload.objects.get(id=id)
csvobject = CSV(upload.filepath)
upload.num_records = csvobject.get_row_count()
upload.num_columns = csvobject.get_column_count()
upload.save()
form = ConfiguratorForm()
row_count = csvobject.get_row_count()
colum_count = csvobject.get_column_count()
first_row = csvobject.get_data(rows=1)
first_two_rows = csvobject.get_data(rows=5)
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 179
很高兴看到csv文件本身,但这可能对你有用,试一试,替换:
file_read = csv.reader(self.file)
Run Code Online (Sandbox Code Playgroud)
有:
file_read = csv.reader(self.file, dialect=csv.excel_tab)
Run Code Online (Sandbox Code Playgroud)
或者,打开一个文件universal newline mode并将其传递给csv.reader,如:
reader = csv.reader(open(self.file, 'rU'), dialect=csv.excel_tab)
Run Code Online (Sandbox Code Playgroud)
或者,使用splitlines(),像这样:
def read_file(self):
with open(self.file, 'r') as f:
data = [row for row in csv.reader(f.read().splitlines())]
return data
Run Code Online (Sandbox Code Playgroud)
小智 50
我意识到这是一个老帖子,但我遇到了同样的问题而没有看到正确的答案所以我会试一试
Python错误:
_csv.Error: new-line character seen in unquoted field
Run Code Online (Sandbox Code Playgroud)
尝试读取Macintosh(OS X格式化前)CSV文件.这些是使用CR作为行尾的文本文件.如果使用MS Office,请确保选择纯CSV格式或CSV(MS-DOS).不要使用CSV(Macintosh)作为保存类型.
我首选的EOL版本是LF(Unix/Linux/Apple),但我不认为MS Office提供了以这种格式保存的选项.
Nim*_*imo 18
如果在mac上发生这种情况(就像它对我做的那样):
CSV (MS-DOS Comma-Separated)运行以下脚本
with open(csv_filename, 'rU') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print ', '.join(row)
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
125235 次 |
| 最近记录: |