我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
Sample.csv包含以下内容
NAME Id No Dept
Tom 1 12 CS
Hendry 2 35 EC
Bahamas 3 21 IT
Frank 4 61 EE
Run Code Online (Sandbox Code Playgroud)
并且python文件包含以下代码
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
Run Code Online (Sandbox Code Playgroud)
当我在python中运行上面的代码时,我得到以下异常
文件"csvformat.py",第4行,in for read in:_csv.Error:iterator应该返回字符串,而不是字节(你是否在文本模式下打开文件?)
我该如何解决?
csv.DictReader我目前正在尝试读取通过 Flask-WTF(orms) 提供的 CSV 文件,并且在尝试通过or加载它时仍然遇到问题pandas。
该文件(一个FileStorage对象)实际上并未上传到任何地方,我正在尝试获取 CSV 中的数据以在我的代码中使用。
这就是我现在尝试使用的方式来获取它pandas
f = form.upload.data
data = pandas.read_csv(f.stream)
logger.debug(data)
Run Code Online (Sandbox Code Playgroud)
然而这返回了错误pandas.errors.EmptyDataError: No columns to parse from file
当我尝试通过这种方式抓住它时csv.reader:
reader = csv.reader(f.read(), delimeter=',')
for row in reader:
logger.debug(row)
Run Code Online (Sandbox Code Playgroud)
我得到了这个错误:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
我在尝试时csv.DictReader也收到了类似的错误。
有没有人尝试过做类似的事情,或者知道这是否可以在不上传文件的情况下实现?我环顾四周,但似乎找不到合适的解决方案。
作为参考,我的 CSV 文件有一个非常基本的格式:
C1,C2
Data,Data
Run Code Online (Sandbox Code Playgroud)
谢谢!