繁体   English   中英

重命名txt文件。 编辑版本:[错误183]该文件已存在时无法创建该文件

[英]Rename txt file. Edited version: [Error 183] Cannot create a file when that file already exists

我正在使用python 2.7x。 我是python的新手,将非常感谢您的帮助。 我已经阅读了许多帖子,包括以下所示的一些关于此错误的信息:

WindowsError:[错误32]该进程无法访问文件,因为该文件正在被另一个进程使用:'new.dat' ->我的文件关闭指令已经在结尾。

python 2 [错误32]该进程无法访问该文件,因为该文件正在被另一个进程使用 ->我不能使用shutil,因为我正在使用的python程序中存在一些错误,并且我无法在计算机上编辑该路径受行政保护。

在Python中重命名文件 ->按照建议进行操作后,出现NameError:未定义名称'rename'...:/

等等等

在尝试纠正我的代码后,我仍然遇到相同的错误。

我想做的是:读取目录中的文件,如果任何文件包含特定的字符串,我都将重命名文本文件(即first.txt到firstfound.txt。)

编辑版本:在重命名文件之前,我尝试移动abc.close():

import os

fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
 if not line.find("scramble") : 
  continue
 oldfile = fname
abc.close() 
if oldfile == fname:
 for title in fname:
    endname = title.find('.txt')
    oldtitle = title[:endname]
    newfile = oldtitle +"found.txt"
    os.rename(oldfile,newfile)

但我有此错误,而不是最后一行。 os.rename(oldfile,newfile)WindowsError:[错误183]该文件已存在时无法创建该文件。 我的文件夹中没有使用新名称的文件。 非常感谢您的建议!

编辑版本2:我也尝试过另一组代码,但它给了我WindowsError:[错误5]访问被拒绝。 我是否可以知道是否由于没有管理员权限而无法重命名txt文件? 谢谢!

import os

fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
 if not line.find("scramble") : 
  continue
 oldfile = fname
abc.close() 

if (oldfile == fname): #+'/' +  "a.txt"
 for title in fname:
    endname = title.find('.txt')
    oldtitle = title[:endname]
    new_file = oldtitle +'/' +  "a.txt"
    os.rename(fname,new_file)

初始版本:我得到的错误是在os.rename行。 “ WindowsError:[错误32]该进程无法访问该文件,因为该文件正在被另一个进程使用”

我的整个程序代码如下所示:

import os

fname = raw_input("Enter file name: ")
#fill in file directory here
abc = open(fname)
for line in abc:
 if not line.find("scramble") : 
  continue
 old_file = fname
 for title in fname:
    endname = title.find('.txt')
    oldtitle = title[:endname]
    new_file = oldtitle +'/' +  "found.txt"
    os.rename(old_file,new_file) ##WindowsError: [Error 32] The process cannot access the file because it is being used by another process
abc.close() 

我不明白为什么这个错误仍然存​​在。 (我已经关闭了所有文件和文件夹)。 非常感谢你!

该问题很可能是由于您在代码中调用open()造成的。 python中的open()函数打开文件进行读取/写入,因此,如果您打开文件,则无法调用重命名,因为它是在另一个位置打开的。

相反,您应该致电

abc.close() 

重命名文件之前。

有关文件I / O的更多信息,请参见此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM