【问题标题】:append text to file. adding text to specified txt file.将文本附加到文件。将文本添加到指定的 txt 文件。
【发布时间】:2018-05-05 06:03:36
【问题描述】:

我正在尝试将文本添加到来自 -a 开关的配置文件。 其余代码确实有效,但不确定谁调用选择配置文件并写入一个新文件以备份到其中。

parser = argparse.ArgumentParser(description='Copy multiple Files from a specified data file')
parser.add_argument('-c', '--configfile', default="config.dat", help='file to read the config from')
parser.add_argument('-l', '--location', default="/home/admin/Documents/backup/",help='Choose location to store files')
parser.add_argument('-a', '--addfile', help='Choose a file to add to list')

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 add_to_file():
    try:
        f = open('configfile','r')
        f.read()
        addto = f.write('addfile')
        f.close()
    except FileNotFoundError:
            pass**
args = vars(parser.parse_args())
read = read_config(args['configfile'])
add = add_to_file(args['addfile'])

当我运行它时,我收到如下错误:

    add = add_to_file(args['addfile'])
TypeError: add_to_file() takes 0 positional arguments but 1 was given

有什么想法我会出错吗?

感谢您的帮助

【问题讨论】:

    标签: python python-3.x append argparse


    【解决方案1】:

    错误有问题:

    add_to_file() takes 0 positional arguments but 1 was given
    

    add_to_file 不接受任何参数,但你传递了一个。

    编辑:这里有一些问题,但我最初的答案是你的直接障碍:

    1. f.write 不返回任何内容,无需分配。
    2. 您永远不会关闭 read_config 中的文件。
    3. 要附加到文件,你需要用a模式打开它,像这样:open('configfile', 'a')而不是r模式
    4. 您在 except 块中过度缩进。另外我什至不确定 pass** 是做什么的。你或许应该让它升起。
    5. 我不完全确定代码在这里试图完成什么。看起来 read_config 将读取文件列表,然后将它们复制到 dest。我明白了。但是add_to_file 做了什么?将更多文件添加到将在后续运行 read_config 时复制的配置?

    对于 #2,请考虑使用上下文管理器。它将为您处理关闭文件。它看起来像这样:

    with open('some_file.txt', 'r'):
        do_some_stuff()
    

    上面的示例将处理打开和关闭文件,即使有异常。

    【讨论】:

    • 感谢您的帮助。我更改为以下内容: def addtofile(test): try: with open('config.dat', 'a') as file: file.write(test + "\n") except FileNotFoundError: logger.error("error message") args = vars(parser.parse_args()) read = read_config(args['configfile']) add = addtofile(args['add']) shutil.SameFileError: 'backup/test.dat' and '/home /admin/Documents/backup/test.dat' 是同一个文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多