python - 在新行上追加文本文件

时间:2017-11-21 22:08:35

标签: 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 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'])

1 个答案:

答案 0 :(得分:1)

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