我读过Why is Python giving me "an integer is required" when it shouldn't be?。对于我的问题,它几乎是一个完整的解决方案,但还不完全。
下面是我的代码:
#! usr/local/bin/python3.6
# coding: utf-8
from os import getcwd, listdir
import psycopg2
from io import open
conn = psycopg2.connect("dbname=ktab user=malikarumi")
cur = conn.cursor()
path = getcwd()
filenames = listdir(path)
for filename in filenames:
with open(filename, 'r', 'utf-16') as f:
f1 = f.read()
cur.execute("INSERT INTO testable (title, content, chron_date, clock)\
VALUES (%s, %s, %s, %s)"),
(filename, f1, '2017-12-30', '23:59:00'),
conn.commit()
cur.close()
conn.close()在阅读了以前的SO post之后,我修改了上面的代码,以指定我想要的io模块,并将os模块限制为我正在使用的两个模块。Sublime Text 3有一个工具提示,指示我正在调用io.open(),但当我运行代码时,它显然是os.open() (我知道是因为这个错误):
(lifeandtimes) malikarumi@Tetuoan2:~/Projects/Progress_Logs/2017$
python ktab_odt4.py
Traceback (most recent call last):
File "ktab_odt4.py", line 17, in <module>
with open(filename, 'r', 'utf-16') as f:
TypeError: an integer is required (got type str)注意:我已经尝试过with io.open()和import io了。在这两种情况下,pylint都发出了尖叫声,解释器给出了我的名字错误。使用'rb'可以通过pylint,但是解释器仍然会给我TypeError。这种情况的解决方法是什么?
发布于 2018-01-02 03:44:23
io.open()的第三个位置参数是buffering,它需要一个整数。您将字符串'utf-16'作为第三个参数进行传递,因此您将得到错误。您需要使用encoding='utf-16'将该值作为关键字参数进行传递。
https://stackoverflow.com/questions/48052594
复制相似问题