小编Nic*_*Nic的帖子

将字典写入文本文件?

我有一本字典,我正在尝试将其写入文件.

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)
Run Code Online (Sandbox Code Playgroud)

然后我有错误

file.write(exDict)
TypeError: must be str, not dict
Run Code Online (Sandbox Code Playgroud)

所以我修复了这个错误,但又出现了另一个错

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))
Run Code Online (Sandbox Code Playgroud)

错误:

file.write(str(exDict))
io.UnsupportedOperation: not writable
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么办,因为我还是python的初学者.如果有人知道如何解决问题,请提供答案.

注意:我使用的是python 3,而不是python 2

dictionary file file-writing python-3.x

59
推荐指数
6
解决办法
15万
查看次数

在python3中发送到程序的stdin

我有文件,main.pychild.py.

我正在尝试将字符串发送到main.py的stdin .

这是我不完整的代码:

main.py

from subprocess import *
import time

def main():
    program = Popen(['python.exe'. 'child.py', 'start'])
    while True: #waiting for'1' to be sent to the stdin
        if sys.stdin == '1':
            print('text)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

child.py

import sys

if sys.argv[1] == 'start':
    inp = input('Do you want to send the argument?\n').lower()
    if inp == 'no':
        sys.exit()
    elif inp == 'yes':
        #Somehow send '1' to the stdin of 1.py while it is …
Run Code Online (Sandbox Code Playgroud)

python stdin python-3.x

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

MD5 散列:必须在散列之前对 Unicode 对象进行编码

我有一些代码可以在 Python 3 中散列字符串

import hashlib
hobj = hashlib.md5()
Run Code Online (Sandbox Code Playgroud)

当我使用命令时:

hobj.update('test')
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: Unicode-objects must be encoded before hashing
Run Code Online (Sandbox Code Playgroud)

python md5 hashlib python-3.x

1
推荐指数
1
解决办法
5343
查看次数

标签 统计

python-3.x ×3

python ×2

dictionary ×1

file ×1

file-writing ×1

hashlib ×1

md5 ×1

stdin ×1