Python:计数器和写入文件的帮助

发布于 2024-08-24 10:58:07 字数 430 浏览 4 评论 0原文

可能的重复:
Python:如何创建连续文件名?

建议使用单独的文件作为计数器来为我的文件提供连续的文件名,但我不明白如何做到这一点。我需要我的文件名具有连续的数字,例如 file1.txt、file2.txt、file3.txt。任何帮助表示赞赏!

编辑: 我的错误,我忘了说代码在执行时会创建一个文件,并且需要一种方法来创建一个具有不同文件名的新的单独文件。

更多编辑: 我基本上正在拍摄屏幕截图并尝试将其写入文件,并且我希望能够拍摄多个屏幕截图而不被覆盖。

Possible Duplicate:
Python: How do I create sequential file names?

I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, file2.txt, file3.txt. Any help is appreciated!

Edit:
My mistake, I forgot to say that the code makes 1 file when it's executed, and needs a way to make a new separate one with a different file name.

More Edit:
I am taking a screen shot basically and trying to write it to a file, and I want to be able to take more than one without it being overwritten.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

落墨 2024-08-31 10:58:07

可能需要更多信息,但如果您想按顺序命名文件以避免名称冲突等,则不一定需要单独的文件来记录当前编号。我假设您想时不时地编写一个新文件,并编号以跟踪事物?

因此,给定一组文件,您想知道下一个有效文件名是什么。

类似于(对于当前目录中的文件):

import os.path

def next_file_name(): 数量 = 1 而真实: file_name = '文件%d.txt' % num 如果不是 os.path.exists(file_name): 返回文件名 数字 += 1

显然,随着目录中文件数量的增加,速度会变慢,因此这取决于您期望有多少文件。

More information probably is needed, but if you want to sequentially name files to avoid name clashes etc you don't necessarily need a separate file to record the current number. I'm assuming you want to write a new file from time to time, numbering to keep track of things?

So given a set of files, you want to know what the next valid file name would be.

Something like (for files in the current directory):

import os.path

def next_file_name(): num = 1 while True: file_name = 'file%d.txt' % num if not os.path.exists(file_name): return file_name num += 1

Obviously though as the number of files in the directory increases this will get slower, so it depends on how many files you expect there to be.

怀里藏娇 2024-08-31 10:58:07

像这样的东西吗?

n = 100
for i in range(n):
  open('file' + str(i) + '.txt', 'w').close()

Something like this?

n = 100
for i in range(n):
  open('file' + str(i) + '.txt', 'w').close()
半枫 2024-08-31 10:58:07

假设的例子。

import os
counter_file="counter.file"
if not os.path.exists(counter_file):
    open(counter_file).write("1");
else:
    num=int(open(counter_file).read().strip()) #read the number
# do processing...
outfile=open("out_file_"+str(num),"w")
for line in open("file_to_process"):
    # ...processing ...
    outfile.write(line)    
outfile.close()
num+=1 #increment
open(counter_file,"w").write(str(num))

Hypothetical example.

import os
counter_file="counter.file"
if not os.path.exists(counter_file):
    open(counter_file).write("1");
else:
    num=int(open(counter_file).read().strip()) #read the number
# do processing...
outfile=open("out_file_"+str(num),"w")
for line in open("file_to_process"):
    # ...processing ...
    outfile.write(line)    
outfile.close()
num+=1 #increment
open(counter_file,"w").write(str(num))
冬天旳寂寞 2024-08-31 10:58:07
# get current filenum, or 1 to start
try:
  with open('counterfile', 'r') as f:
    filenum = int(f.read())
except (IOError, ValueError):
  filenum = 1

# write next filenum for next run
with open('counterfile', 'w') as f:
  f.write(str(filenum + 1))

filename = 'file%s.txt' % filenum
with open(filename, 'w') as f:
  f.write('whatever you need\n')
  # insert all processing here, write to f

在 Python 2.5 中,您还需要第一行 from __future__ import with_statement 才能使用此代码示例;在 Python 2.6 或更高版本中,您不需要(您也可以使用比 % 运算符更优雅的格式化解决方案,但这是一个非常小的问题)。

# get current filenum, or 1 to start
try:
  with open('counterfile', 'r') as f:
    filenum = int(f.read())
except (IOError, ValueError):
  filenum = 1

# write next filenum for next run
with open('counterfile', 'w') as f:
  f.write(str(filenum + 1))

filename = 'file%s.txt' % filenum
with open(filename, 'w') as f:
  f.write('whatever you need\n')
  # insert all processing here, write to f

In Python 2.5, you also need a first line of from __future__ import with_statement to use this code example; in Python 2.6 or better, you don't (and you could also use a more elegant formatting solution than that % operator, but that's a very minor issue).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文