相关疑难解决方法(0)

困惑的python文件模式"w +"

来自doc,

模式'r +','w +'和'a +'打开文件进行更新(注意'w +'截断文件).将"b"附加到模式以在二进制模式下打开文件,在区分二进制文件和文本文件的系统上; 在没有这种区别的系统上,添加'b'没有效果.

w +:打开文件进行书写和阅读.如果文件存在,则覆盖现有文件.如果该文件不存在,则创建一个用于读写的新文件.

但是,如何读取打开的文件w+

python io file

178
推荐指数
5
解决办法
27万
查看次数

Python中的错误挑选:io.UnsupportedOperation:读取

我正在尝试学习如何pickle在python中保存对象.但是,当我使用下面的示例代码时,我收到以下错误:io.UnsupportedOperation: read追溯到favorite_color = pickle.load(f_myfile).我找不到这个特殊错误的好解释.我做错了什么,如何纠正?

import pickle  # or import cPickle as pickle

# Create dictionary, list, etc.
favorite_color = { "lion": "yellow", "kitty": "red" }

# Write to file
f_myfile = open('myfile.pickle', 'wb')
pickle.dump(favorite_color, f_myfile)
f_myfile.close()

# Read from file
f_myfile = open('myfile.pickle', 'wb')
favorite_color = pickle.load(f_myfile)  # variables come out in the order you put them in
f_myfile.close()
Run Code Online (Sandbox Code Playgroud)

python pickle

13
推荐指数
1
解决办法
2万
查看次数

Python - 附加到pickle列表

我正在努力在一个腌制文件中附加一个列表.这是代码:

#saving high scores to a pickled file

import pickle

first_name = input("Please enter your name:")
score = input("Please enter your score:")

scores = []
high_scores = first_name, score
scores.append(high_scores)

file = open("high_scores.dat", "ab")
pickle.dump(scores, file)
file.close()

file = open("high_scores.dat", "rb")
scores = pickle.load(file)
print(scores)
file.close()
Run Code Online (Sandbox Code Playgroud)

我第一次运行代码时,会打印出名称和分数.

第二次运行代码时,它会输出2个名称和2个分数.

第三次运行代码时,它会输出第一个名称和分数,但它会覆盖第二个名称并使用我输入的第三个名称和分数进行分数.我只是想让它继续添加名称和分数.我不明白为什么它保存名字并覆盖第二个名字.

python append pickle

12
推荐指数
2
解决办法
2万
查看次数

io.UnsupportedOperation:不可读

我正在研究一个问题,即创建一个程序来获取文件的用户输入,然后在文件中删除用户指定的字符串.我不确定如何从我所拥有的(下面)到问题所要求的内容.一如既往,非常感谢任何和所有的帮助.

def main():
    outfile = open(input("Enter a file name: "), "a")
    string = input("Enter the string to be removed: ")
    for string in outfile.readlines():
        string = string.replace(string, "")
    outfile.close()
    print("Done")

main()
Run Code Online (Sandbox Code Playgroud)

我采取了其中一个建议,并尝试让它工作,但正如我在下面的评论中所说,下面的代码不会返回错误,它会创建一个空文件.我错过了将新文件作为删除字符串的旧文件而丢失的内容?

def main():
    inpath = input("Enter an input file: ")
    line = input("Enter what you want to remove: ")
    outpath = input("Enter an output file: ")
    with open(inpath, "r") as infile, open(outpath, "w") as outfile:
        for line in infile:
            outfile.write(line.replace(line, "") + "\n")
    print("Done.")

main()
Run Code Online (Sandbox Code Playgroud)

python python-3.x

4
推荐指数
1
解决办法
3万
查看次数

标签 统计

python ×4

pickle ×2

append ×1

file ×1

io ×1

python-3.x ×1