打开和覆盖文件时是否可以只使用 "wb" ?
Is it possible to only use "wb" when opening and overwriting a file?
如果我想打开一个文件,取消选中其中的一个对象,然后稍后覆盖它,可以只使用
data = {} #Its a dictionary in my code
file = open("filename","wb")
data = pickle.load(file)
data["foo"] = "bar"
pickle.dump(data,file)
file.close()
或者我是否必须先使用 "rb" 然后再使用 "wb" (每个都使用 with 语句)这就是我现在正在做的。请注意,在我的程序中,在打开文件和关闭文件之间有一个哈希算法,这是字典数据的来源,我基本上希望能够只打开一次文件而不必执行两次 with 语句
您可以使用 wb+
打开文件进行读写
这个问题有助于理解python各个读写条件的区别,但是在最后加上+
通常总是打开文件进行读写
Confused by python file mode "w+"
想读就写文件,完全不要使用涉及w
的模式;他们都在打开文件时截断文件。
如果已知文件存在,请使用模式 "rb+"
,这会打开现有文件进行读写。
您的代码只需改动一点点:
# Open using with statement to ensure prompt/proper closing
with open("filename","rb+") as file:
data = pickle.load(file) # Load from file (moves file pointer to end of file)
data["foo"] = "bar"
file.seek(0) # Move file pointer back to beginning of file
pickle.dump(data, file) # Write new data over beginning of file
file.truncate() # If new dump is smaller, make sure to chop off excess data
如果我想打开一个文件,取消选中其中的一个对象,然后稍后覆盖它,可以只使用
data = {} #Its a dictionary in my code
file = open("filename","wb")
data = pickle.load(file)
data["foo"] = "bar"
pickle.dump(data,file)
file.close()
或者我是否必须先使用 "rb" 然后再使用 "wb" (每个都使用 with 语句)这就是我现在正在做的。请注意,在我的程序中,在打开文件和关闭文件之间有一个哈希算法,这是字典数据的来源,我基本上希望能够只打开一次文件而不必执行两次 with 语句
您可以使用 wb+
打开文件进行读写
这个问题有助于理解python各个读写条件的区别,但是在最后加上+
通常总是打开文件进行读写
Confused by python file mode "w+"
想读就写文件,完全不要使用涉及w
的模式;他们都在打开文件时截断文件。
如果已知文件存在,请使用模式 "rb+"
,这会打开现有文件进行读写。
您的代码只需改动一点点:
# Open using with statement to ensure prompt/proper closing
with open("filename","rb+") as file:
data = pickle.load(file) # Load from file (moves file pointer to end of file)
data["foo"] = "bar"
file.seek(0) # Move file pointer back to beginning of file
pickle.dump(data, file) # Write new data over beginning of file
file.truncate() # If new dump is smaller, make sure to chop off excess data