简体   繁体   English

调用io.open(),而不是os.open()

[英]Calling io.open(), not os.open()

I have read Why is Python giving me "an integer is required" when it shouldn't be? 我已经读过Python为什么不应该给我一个“需要整数”的信息呢? . It is nearly a complete solution for my issue, but not quite. 对于我的问题,这几乎是一个完整的解决方案,但还不完全是。

Here is my code: 这是我的代码:

#! 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()

After reading the older SO post, I modified my code as above, so as to specify which io module I wanted and restrict the os modules to the two I was using. 阅读了较早的SO文章之后,我如上所述修改了我的代码,以便指定我想要的io模块并将os模块限制为我正在使用的两个模块。 Sublime Text 3 has a tooltip which indicates I am calling io.open() , but when I run the code, it is plainly os.open() (I know because of the error): 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)

Note: I already tried with io.open() and import io . 注意:我已经尝试with io.open()import io In both cases pylint squawked and the interpreter gave me name errors. 在这两种情况下,pylint都尖叫着,口译员给了我名字错误。 Using 'rb' got past pylint but the interpreter still gives me the TypeError . 使用'rb'过去了pylint,但是解释器仍然给我TypeError What is the workaround for this situation? 这种情况下的解决方法是什么?

The third positional parameter to io.open() is buffering , which requires an integer. io.open()的第三个位置参数是buffering ,它需要一个整数。 You are passing the string 'utf-16' as the third parameter, thus the error you're getting. 您将字符串'utf-16'作为第三个参数传递,因此得到了错误。 You need to use encoding='utf-16' to pass that value as a keyword parameter. 您需要使用encoding='utf-16'将该值作为关键字参数传递。

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

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