需要一个整数?打开()

问题描述 投票:36回答:5

我有一个非常简单的python脚本,它应该扫描一个文本文件,其中包含格式为id ='value'的行,并将它们放入一个dict中。 python模块名为chval.py,输入文件名为in.txt。这是代码:

import os,sys
from os import *
from sys import *

vals = {}

f = open(sys.argv[1], 'r')

for line in val_f:
    t = line.split('=')
    t[1].strip('\'')
    vals.append(t[0], t[1])

print vals

f.close()

当我尝试运行它时,我得到:

Traceback(最近一次调用最后一次): 文件“chval.py”,第9行,在? f = open(sys.argv [1],'r')TypeError:需要一个整数

我正在使用python 2.4 ...因为我一直被要求不使用任何更新的东西,是否有一些我不知道的open()?为什么要整数?

该行之后的任何内容都是未经测试的。简而言之:为什么它会给我错误,我该如何解决?

python file-io integer argv
5个回答
59
投票

因为你做了from os import *,你(意外)使用os.open,它确实需要一个整数标志而不是文本“r”或“w”。取出那条线,你就会超越那个错误。


11
投票

没有充分理由不做import * from wherever(并没有很多)。

您的代码正在使用os.open()函数而不是内置的open()函数。如果你真的想使用os.open(),请执行import os然后调用os.open(....)。无论打开哪个打开,请阅读有关所需参数的文档。


11
投票

另外值得注意的是,从Python 2.6开始,内置函数open()现在是io.open()函数的别名。甚至考虑删除Python 3中的内置open()并要求使用io.open,以避免因“from blah import *”之类的事情导致意外的命名空间冲突。在Python 2.6+中你可以编写(也可以认为这种风格是很好的做法):

import io
filehandle = io.open(sys.argv[1], 'r')

1
投票

提供这些参数解决了我的问题:

with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file:
    file.write(result)

0
投票

http://www.tutorialspoint.com/python/os_open.htm你也可以保持你的进口和使用

file = os.open(“foo.txt”,mode)

而模式可能是:

os.O_RDONLY: open for reading only
os.O_WRONLY: open for writing only
os.O_RDWR : open for reading and writing
os.O_NONBLOCK: do not block on open
os.O_APPEND: append on each write
os.O_CREAT: create file if it does not exist
os.O_TRUNC: truncate size to 0
os.O_EXCL: error if create and file exists
os.O_SHLOCK: atomically obtain a shared lock
os.O_EXLOCK: atomically obtain an exclusive lock
os.O_DIRECT: eliminate or reduce cache effects
os.O_FSYNC : synchronous writes
os.O_NOFOLLOW: do not follow symlinks
© www.soinside.com 2019 - 2024. All rights reserved.