Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将字符串数组输出到Python中的文件_Python_Python 3.x - Fatal编程技术网

如何将字符串数组输出到Python中的文件

如何将字符串数组输出到Python中的文件,python,python-3.x,Python,Python 3.x,如何将列表写入.txt文件 这是我的密码: num_of_mangoes[] for i in range(shops): num_of_mangoes.append([]) for j in range(fruits): num_of_mangoes[i].append(j) return num_of_mangoes 其他信息: 店铺数量=200000 水果数量=500 假设实际代码为: 芒果的数量=[] 对于范围内的i(商店): 芒果的数量。追加([]) 对于范围

如何将列表写入.txt文件

这是我的密码:

num_of_mangoes[]
for i in range(shops):
  num_of_mangoes.append([])
   for j in range(fruits):
     num_of_mangoes[i].append(j)
 
return num_of_mangoes
其他信息:

  • 店铺数量=
    200000
  • 水果数量=
    500

  • 假设实际代码为:

    芒果的数量=[] 对于范围内的i(商店): 芒果的数量。追加([]) 对于范围内的j(水果): 芒果的数量[i].附加(j) 我建议使用将其导出到文件

    导入json
    打开(“num_of_mangoes.txt”,“w”)作为文件:
    dump(文件,芒果数)
    
    如果要从文件中读取列表,可以执行以下操作:

    打开(“num_of_mangoes.txt”,“r”)作为文件:
    num_of_mangoes=json.load(文件)
    
    尝试使用以下方法:

    # we'll use this module later on
    import json
    
    # define the number of shops and fruits    
    shops, fruits = 200000, 500
    
    # create the "num_of_mangoes" list using a list comprehension
    num_of_mangoes = [[j for j in range(fruits)] for i in range(shops)]
    
    # open the file (create if not exists), write to it, then close it
    f = open("num_of_mangoes.txt", "w")
    # NOTE: the "separators" and "indent" arguments are used to minify the json
    f.write(json.dumps(num_of_mangoes, separators = (',', ':'), indent = 0))
    f.close()
    
    以下是同一代码的单行程序版本:

    import json; with open("num_of_mangoes.txt", "w") as f: f.write(json.dumps([[j for j in range(500)] for i in range(200000)], separators = (',', ':'), indent = 0))
    
    缩小:

    import json;with open("num_of_mangoes.txt","w") as f:f.write(json.dumps([[j for j in range(500)] for i in range(200000)],separators=(',',':'),indent=0))
    
    警告:您的JSON文件将(不可思议)大,不要使用Atom之类的文本编辑器打开它,它可能会冻结您的计算机,请改用
    cat
    head
    tail
    命令

    警告:鉴于您拥有
    200000(二十万)家店铺,创建此列表需要一段时间,我建议您出于测试目的降低该数字


    祝你好运。

    你试过什么?您具体需要什么帮助?我没有尝试输出到文本文件中。。我是来寻求帮助的你需要先尝试一下你需要的帮助。有许多关于写入文件的教程。这一次你得到了答案,但请在将来确保你首先努力自学。这是我在这里的期望。谢谢,我会在这里发布之前在网上查找资源。我以为这是我的资源!非常感谢。我会试试的。非常感谢。不客气。