【问题标题】:Python: error when trying to write or overwrite a text file in a directoryPython:尝试在目录中写入或覆盖文本文件时出错
【发布时间】:2016-02-25 18:31:07
【问题描述】:

我写了一个由两个函数组成的python脚本:

note() : 在名为 target_dir 的目录中写入文本文件。

file_exist():检查以字符串“note”开头的文本文件是否已经存在于 target_dir 中。如果是这种情况,我想通过再次运行 note() 函数来覆盖文本文件。代码如下:

import glob, os, shutil, time


def note():
    """ Write the info a in a txt file"""
    print 'Please enter few info:\n '
    a = raw_input('Aim: ')     
    add = raw_input('Additional info: ')
    file_name = 'note_' + time.strftime('%d%m%Y') + '.txt'    #which is: note_23112015.txt
    myfile = open(file_name, 'w')
    myfile.write('Aim: '+ a +'\n')      
    myfile.write('Additional info: '+ add +'\n')
    myfile.close()
    shutil.copy2(file_name, target_dir)


def file_exist():
    """Check if a file starting with the string 'note' already exist."""
    txt = [i for i in os.listdir(target_dir) if os.path.isfile(os.path.join(target_dir,i)) and 'note' in i]
    if txt:
        inp = raw_input('Text File already exist, do you want overwrite?(y or n)')
        if inp == 'y':
            note()
    else:
        note()

if __name__ == "__main__":
    # Change the directory path    
    target_dir = 'C:/Users/data' # target directory
    file_exist()   

当我尝试运行脚本时,文本文件会正确生成,但我也会收到一堆以以下结尾的错误:

Error: note_23112015.txt and `C:/Users/data\note_23112015.txt` are the same file

有人知道这段代码有什么问题吗? 谢谢你

【问题讨论】:

  • 错误发生在哪一行?如果你的一堆错误实际上是一个堆栈跟踪,它应该在那里告诉你。
  • 代码对我来说运行良好,没有错误。
  • 也许,你在你的目标目录中。
  • 是的,我是!现在你告诉我我尽量不要在目标目录中,它工作正常!!如果我从目标目录运行脚本,为什么它不起作用?我该如何解决?非常感谢
  • shutil.copy2(file_name, target_dir) 从当前目录复制到目标目录。如果当前和目标相同,它将失败。您可以使用os.path.normpath(os.path.basename(target_dir)) == os.getcwd() 并跳过副本。

标签: python windows file


【解决方案1】:

shutil.copy2(file_name, target_dir) 行中,您将文件复制到它已经在的路径中。您需要任一

1) 更改目标目录或搜索目录(当前从您的工作目录中提取),使它们彼此不匹配

2) 更改输出文件的名称。

但是,在重新阅读您的描述后,听起来您可以完全删除 copy2 行。您需要两份更新后的文件吗?

编辑:

根据 OP 的要求,我会写下我的话:

shutil.copy2(file_name, target_dir)

【讨论】:

  • 我只需要在我的目标目录中编写文本文件,独立于我运行脚本的位置,你能写下你的话吗?谢谢
  • @diegus,目前还不太清楚你想要什么。你想要两个文本文件的副本吗?如果是这样,您是要保留原样,还是要更新后的文本文件的两个副本?原始文本文件是否已经在目标目录中?您的源目录和目标目录是相同的;你想要/需要这样吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
相关资源
最近更新 更多