相关疑难解决方法(0)

在Python中使用大写字母和数字生成随机字符串

我想生成一个大小为N的字符串.

它应由数字和大写英文字母组成,例如:

  • 6U1S75
  • 4Z4UKK
  • U911K4

我怎样才能以pythonic方式实现这一目标?

python string random

1247
推荐指数
15
解决办法
81万
查看次数

生成临时文件名而无需在Python中创建实际文件

stackoverflow中的问题编号10501247给出了如何在Python中创建临时文件的答案.
在我的情况下,我只需要有临时文件名.
调用tempfile.NamedTemporaryFile()会在实际创建文件后返回文件句柄.
有办法获取文件名吗?

# Trying to get temp file path
tf = tempfile.NamedTemporaryFile()
temp_file_name = tf.name
tf.close()
# Here is my real purpose to get the temp_file_name
f = gzip.open(temp_file_name ,'wb')
...
Run Code Online (Sandbox Code Playgroud)

python temporary-files

71
推荐指数
8
解决办法
3万
查看次数

如何使用tempfile.NamedTemporaryFile()?

我正在开发一个Python脚本,需要创建大约50个不同的临时文件,这些文件在脚本过程中经常被附加并在最后合并.我确信该tempfile模块可以做我需要的,但我无法弄清楚如何阅读文档.

我想使用临时文件(而不是变量)来节省系统内存,因为这些数据块会随着脚本处理数万个其他文件而变大.

下面的代码块是我正在用于在非临时目录中创建这些文件(非暂时)的hack:

item = (string from another file)   # string must id file for future use
tmpfile = 'tmpfiles/' + item
if item not in totalitems:
   totalitems.add(item)
   with open(tmpfile, 'w') as itemfile:
      output = some stuff
      tmpfile.write(output)
else:
   with open(tmpfile, 'a') as itemfile:
      output = different stuff
      tmpfile.write(output)
Run Code Online (Sandbox Code Playgroud)

我想我需要的是tempfile.NamedTemporaryFile().根据文件:

可以从文件对象的名称成员中检索该名称.

不幸的是,我不明白这意味着什么.当我在我正在处理的文件中再次运行其相应的"项目"时,我只需要能够稍后再次调用每个文件.我认为这是相当直接的,我只是在密集.如果它很重要,我有Python 2.7.1和3.2.3的这个脚本的版本.我真的只需要一个人或另一个人去工作; 我创造了两个作为学习练习.

python temporary-files

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

标签 统计

python ×3

temporary-files ×2

random ×1

string ×1