简体   繁体   English

fp.read无法读取整个csv文件

[英]fp.read not reading entire csv file

I am attaching a csv file and sending it as an email. 我要附加一个csv文件,并将其作为电子邮件发送。 Same code has been working for my other codes but in this weird case it truncates the data in csv. 我的其他代码也使用了相同的代码,但是在这种奇怪的情况下,它将截断csv中的数据。 Actual csv is 11 kb but attachment is of 8 kb. 实际的csv为11 kb,但附件为8 kb。 Actual file has 1400+ rows where as attachment only has some 1100 rows. 实际文件有1400多行,其中附件只有1100行。

fp = open(path)
msg1 = MIMEText(fp.read())
print os.path.getsize(path)
attachment = msg1.add_header('Content-Disposition', 'attachment',     filename=name)
msg.attach(msg1)
print "Attached " + name
fp.close()

Issue is in this line of code - msg1 = MIMEText(fp.read()) , but I'm not able to figure out a solution. 问题在这行代码中msg1 = MIMEText(fp.read()) ,但是我找不到解决方案。

We can't reproduce your problem without the original file, so this is only a guess. 如果没有原始文件,我们将无法重现您的问题,因此这只是一个猜测。

The default behavior of open('file_path') is opening the file in text mode. open('file_path')的默认行为是以文本模式打开文件。 If your CSV contains an EOF (end-of-file) character, then the fp.read() method may not return the whole file in some platforms. 如果CSV包含EOF(文件结尾)字符,则fp.read()方法在某些平台上可能不会返回整个文件。

Try to open the CSV in binary mode: 尝试以二进制模式打开CSV:

fp = open(path, 'rb')

[edit] [编辑]

I'm unable to reproduce your problem. 我无法重现您的问题。

>>> mt = MIMEText(open('/tmp/test_file.csv').read())
>>> len(mt.as_string().split('\n'))
1165

This has exactly the same number of lines of the original file plus the MIME headers: 这与原始文件加上MIME标头的行数完全相同:

$ wc -l /tmp/test_file.csv
1160 /tmp/test_file.csv

Please identify and closely inspect the shortest program necessary to reproduce the problem or this question will probably be closed because while similar questions may be on-topic here, as currently stated this one is unlikely to help future readers. 请确定并仔细检查重现该问题所需的最短程序,否则该问题可能会结束,因为尽管类似的问题可能在此处引起关注,但如当前所述,此问题不太可能对将来的读者有所帮助。

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

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