简体   繁体   English

从FTP文件夹读取csv

[英]Reading csv from FTP folder

I am trying to read csv file from FTP Folder 我正在尝试从FTP文件夹读取csv文件

ftp = FTP('adr')  
ftp.login(user='xxxx', passwd = 'xxxxx')
r = StringIO()
ftp.retrbinary('RETR /DataLoadFolder/xxx/xxx/xxx/'+str(file_name),r.write)
r.seek(0)
csvfile1 = csv.reader(r,delimiter=';')
input_file = [list(line) for line in csv.reader(r)] ----- Error

getting an error at last line as 在最后一行出现错误

new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

My csv file 我的csv文件

在此处输入图片说明

Text Version 文字版本
在此处输入图片说明

There are whites spaces at the end of each row (after 17.00) 每行末尾(17.00之后)都有空格

Data starts from second row 数据从第二行开始

what does the error mean? 错误是什么意思? Any help would be much appreciated. 任何帮助将非常感激。

The error message simply asking how you'd want to handle the newline differently due to historical reasons, you can read the explanation here . 错误消息只是询问由于历史原因您希望如何以不同方式处理换行符,您可以在此处阅读说明。

To solve the issue, specify the newline on StringIO like this: 要解决此问题,请在StringIO上指定newline ,如下所示:

r = StringIO(newline='')

According to StringIO documentation . 根据StringIO文档 If newline is set to None, newlines are written as \\n on all platforms, but universal newline decoding is still performed when reading. 如果将换行符设置为“无”,则换行符在所有平台上均写入\\n ,但是在读取时仍会执行通用换行符解码。

I could partially reproduce and fix. 我可以部分复制和修复。 The error is caused by a line containing a bad end of line. 该错误是由包含错误的行尾的行引起的。 I could reproduce by adding a line \\r \\n at the end of an otherway valid csv file. 我可以通过在有效的csv文件的末尾添加\\r \\n行来进行复制。

A simple way to fix it is to use a filter to eliminate blank lines and clean end of lines: 一种简单的解决方法是使用过滤器消除空白行并清理行尾:

def filter_bytes(fd):
    for line in fd:
        line = line.strip()
        if len(line) != 0:
            yield(line + b'\r\n')

Once this is done, your code could become: 完成此操作后,您的代码将变为:

ftp = FTP('adr')  
ftp.login(user='xxxx', passwd = 'xxxxx')
r = BytesIO()
ftp.retrbinary('RETR /DataLoadFolder/xxx/xxx/xxx/'+str(file_name),r.write)
r.seek(0)
csvfile1 = csv.reader(filter_bytes(r),delimiter=';')
input_file = list(csvfile1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM