【问题标题】:How to save a .doc file many times with different names in the same folder [duplicate]如何在同一个文件夹中多次保存不同名称的.doc文件[重复]
【发布时间】:2021-09-11 09:53:41
【问题描述】:

我的文件夹中有一个 .doc 文件。我想用不同的名称多次保存同一个 .doc 文件。

例子:

我有一个名为 myfile.doc 的 .doc 文件。

我希望将其保存为myfile1.docmyfile2.docmyfile3.doc

最多需要对 30 个这样的文件执行此操作。

如何在 Python 中做到这一点?

我试过这个脚本。但是有一个错误:-

import shutil

dateoffile = input('Please Enter 4 Digit Date')
filenumber = input('Please Enter File Number')
hyphen1 = '-'
doctrname = 'KW'
hyphen2 = '-'
year = '2011'

original = 'dateoffile+hyphen1+doctrname+hyphen2+year.doc'
for i in range(1,31): # creates 30 files named from 1 to 30
    new = filenumber+i+'.doc' # the +i+ is used to have 30 different names and not crash
    shutil.copyfile(original, new) # You can even do original='pathtofile/orienter code hereginaldocfile.doc' and new='pathtonewfile/newdocfile'+i+'.doc'

错误是:-

new = filenumber+i+'.doc' # +i+ 用于拥有 30 个不同的名称并且不会崩溃 TypeError:只能将str(不是“int”)连接到str

你能解释一下为什么会这样吗???

【问题讨论】:

  • 到目前为止,您尝试了哪些方法,遇到了哪些问题?你能把这些都贴出来吗?

标签: python python-3.x rename .doc


【解决方案1】:

你可以试试这样的:

import shutil

original = 'myfile.doc'
number=int(input("Enter a number to name your files : "))
for i in range(1,31): # creates 30 files named from 1 to 30
    num = number+i
    new = 'myfile'+str(num)+'.doc' # the +num+ is used to have 30 different names and not crash
    shutil.copyfile(original, new) # You can even do original='pathtofile/originaldocfile.doc' and new='pathtonewfile/newdocfile'+str(num)+'.doc'

这应该可以工作

【讨论】:

  • 我试过你的代码。我修改了你的脚本。但它来了一个错误。代码在我的问题描述中
  • @Hacker--RohanRaj 看起来很正常,你的original 只是一个不会改变的字符串,你要做的就是像这样从字符串中取出+'dateoffile'+'hyphen1'+'doctrname'+'hyphen2'+'year.doc'。尝试复制此文件时,代码找不到您的文件,它正在寻找一个名为:'dateoffile+hyphen1+doctrname+hyphen2+year.doc' exaclty 的文件,它没有其中的变量值。看看我的代码,我编辑了它,它试图将 int 添加到一个字符串中,这是我的错,我没有读两遍^^
  • 谢谢你告诉我。但这并不是我想要的。我想要那个,如果我给输入为 1,另一个文件应该命名为 2,另一个文件应该命名为 3。我说的是,如果我给输入为 3452,输出文件应该命名为 3453,并且其他输出文件应命名为 3454,其他输出文件应命名为 3455。数字应加 1。如果您知道,请告诉我解决方案
  • 我们开始@Hacker--RohanRaj,您现在可以输入您的文件编号
  • 感谢您的脚本,但不完全是。为什么它以没有这样的文件或目录出现:'myfile.doc'。我想要它以我想要创建一个 .doc 文件的方式。你能删除那个原件,这样我就可以创建文件而不是复制不同名称的文件???
猜你喜欢
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多