【问题标题】:Python argument to write to different filePython参数写入不同的文件
【发布时间】:2019-05-04 22:29:10
【问题描述】:

我是 Python 新手,希望在将我的伪代码转换为真实代码方面获得一些帮助。我目前有一个完成以下任务的python脚本:

  1. 读取日志文件
  2. 从日志文件创建一个二维时间戳数组
  3. 打开一个数据文件
  4. 比较时间戳(第一列),如果值为 IN 或介于二维数组中的值之间,则在数据文件的最后一列中标记“1”。如果不是,请标记为 0。

我的目标是配置一个可选的命令行参数,但如果给定,会将 0 或 1 写入名为“output.csv”的输出文件,而不是写入数据文件。

目前,已创建 output.csv,但不仅仅是 1 或 0 分类。它本质上将整个 data.csv(即读入)文件重写为 output.csv(应该写入)

有人能帮我吗?我目前有一个完成以下任务的python脚本:

  1. 读取日志文件
  2. 从日志文件创建一个二维时间戳数组
  3. 打开一个数据文件
  4. 比较时间戳(第一列),如果值为 IN 或介于二维数组中的值之间,则在数据文件的最后一列中标记“1”。如果不是,请标记为 0。

我的目标是配置一个可选的命令行参数,但如果给定,会将 0 或 1 写入名为“output.csv”的输出文件,而不是写入数据文件。

如何编辑我当前的脚本以不重写整个 data.csv 文件,而只重写 isBad 0 或 1 指示符?

import re
import csv
import codecs
import argparse

#Configuring arguments and variables
################################################

parser = argparse.ArgumentParser(description='This script is used to automatically classify the workbench operations. If the operation was performed by a human, it will be marked appropriately. If it was done by a machine, it will be marked appropriately.')
parser.add_argument('-d', '--data', required=True, help='The data.csv produced by the workbench')
parser.add_argument('-r', '--log', required=True, help='The log file used to appropriately label the data')
parser.add_argument('-n', '--new', required=False, help='Flag to create output.csv of markings instead of marking data.csv', action="store_true")
args = parser.parse_args()

if (args.new):
        print("You selected to create a new log")

print('data.csv:', args.data)
print('log:', args.log)

filepath = args.log
csv_filepath = args.data

tempStart = ''
tempEnd = ''

################################################

print("                                ")
print("Starting Script")
print("                                ")

#open the log
with open(filepath) as myFile:
    #read the log
    all_logs = myFile.read()
myFile.close()

#Create regular expressions
starting_regex = re.compile(r'\[(\d+)\s+s\]\s+Initializing\s+Workbench')
ending_regex = re.compile(r'\[(\d+)\s+s\]\s+Log\s+File\s+Completed.\s+Stopping!')

#Create arrays of start and end times
start_times = list(map(int, starting_regex.findall(all_logs)))
end_times = list(map(int, ending_regex.findall(all_logs)))

#Create 2d Array
timeArray = list(map(list, zip(start_times, end_times)))

#Print 2d Array
print(timeArray)

print("                                ")
print("Completed timeArray construction")
print("                                ")

#Open the csv file as a reader
with open(csv_filepath, 'rb') as csvfile:
    reader = csv.reader(codecs.iterdecode(csvfile, 'utf-8'))
    input_rows = [row for row in reader]


#Open the csv file as a writer
with open('output.csv', 'w') as outputfile:
    writer = csv.writer(outputfile)

    # loop through the rows, set the currVal to the value of the first column (timestamp)
    for row in input_rows:
        currVal = int(row[0])
        isBad = '0'

        for interval in timeArray:
            if interval[0] <= currVal <= interval[1]:
                isBad = '1'
                break

        writer.writerow(row + [isBad])

print("Script completed")

【问题讨论】:

  • 另外,创建一个新文件:stackoverflow.com/questions/48959098/…
  • 感谢您的反馈,SPYBUG96。我认为答案可能会被采纳为您的两个 cmets 的融合,但我认为这不是重复的,因为这里的特定应用程序对于两个链接都是独一无二的。
  • 使 new-log 成为 store_true 参数。它的默认值为False,如果给定True。正如所写,它需要一个参数,默认值为None
  • 在调试argparse 应用程序时,print(args) 最好查看解析器为各种输入生成的确切内容。这样,当您尝试在代码中使用 args 时,您就不会猜到了。

标签: python arguments parameter-passing argparse


【解决方案1】:

经过足够的调试,我找到了需要更改的行。
writer.writerow(row + [isBad]) 必须是 writer.writerow([isBad])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2019-04-24
    相关资源
    最近更新 更多