python-追加到新行的文本文件

python-追加到新行的文本文件,python,python-3.x,Python,Python 3.x,正在尝试将一行添加到config.dat(addtofile部分)。这只工作一次,一旦我尝试在这里添加第二行,它就会失败 raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) shutil.SameFileError: 'backup/file1' and '/home/admin/Documents/backup/file1' are the same file 代码正在抱怨上述问题: 任何建议 def

正在尝试将一行添加到config.dat(addtofile部分)。这只工作一次,一旦我尝试在这里添加第二行,它就会失败

raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
shutil.SameFileError: 'backup/file1' and '/home/admin/Documents/backup/file1' are the same file
代码正在抱怨上述问题: 任何建议

def read_config(data):
    try:
        dest = '/home/admin/Documents/backup/'
        # Read in date from config.dat
        data = open(data)
        # Interate through list of files '\n'
        filelist = data.read().split('\n')
        # Copy through interated list and strip white spaces and empty lines
        for file in filelist:
            if file:
                shutil.copy(file.strip(), dest)
    except FileNotFoundError:
        logger.error("Config file not found")
        print ("Config File not found")


def addtofile(add_config):
    try:
        with open('config.dat', 'a') as file:
            file.write(add_config + "\n")
    except FileNotFoundError:
        logger.error("error message")
        print ("error message here")

args = vars(parser.parse_args())
read = read_config(args['configfile'])
add = addtofile(args['add'])

问题是您已经以只读(默认)模式打开了文件。当您尝试打开它进行附加时,它仍然处于打开状态。读取数据后关闭文件,然后可以写入。

欢迎使用StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。您是否注意到。。。谢谢