在python中从属性文件读取文件名

2024-06-25 22:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用DictWriter读取文本文件并写入CSV。现在我想为几个文本文件实现相同的代码,并写入不同的CSV文件。我想使用properties.py文件来实现这个目的,比如:

input1 = "file1.txt"  
output1 = "mycsv1.csv" 

input2 = "file2.txt"  
output2 = "mycsv2.csv"

等等。你知道吗

我尝试使用import和链接中指定的其他方法,如“what would be a quick way to read a property file in python?”和“Using ConfigParser to read a file without section name”,但无法解决此问题。你知道吗

我的部分代码:

with open("mycsv1.csv") as f:
    writer = csv.DictWriter(f, ['name', 'age', 'addr'], delimiter=',')
    writer.writeheader()
    with open("file1.txt") as fil:
    # rest of the operations

如何更改代码以使用properties.py文件,即逐个读取属性文件中的每个输入文件,并将输出存储在相应的输出csv中?你知道吗


Tags: 文件csvto代码namepytxtread
1条回答
网友
1楼 · 发布于 2024-06-25 22:59:06

我建议使用函数定义中的*args来帮助实现这一点。本质上:

def main(*args):
    for input in args:
        # Your code to run per file
        with open(input) as f:
            # etc etc etc

引用:https://www.geeksforgeeks.org/args-kwargs-python/

要使用上述方法,现在将其称为:

main('file1.txt', 'file2.txt', ... , 'fileX.txt')

如果将properties.py作为python properties.py运行,情况确实会发生一些变化。如果是这样,那么您可以利用主函数中的sys.argv(我的个人偏好)或argparse(参考:How to read/process command line arguments?)。你知道吗

以上内容将允许您执行以下操作:

python properties.py input1.txt input2.txt ... inputX.txt

相关问题 更多 >