Home > other >  Applying python script to file
Applying python script to file

Time:04-23

This is a simple ask but I can't find any information on how to do it: I have a python script that is designed to take in a text file of a specific format and perform functions on it--how do I pipe a test file into the python script such that it is recognized as input()? More specifically, the Python is derived from skeleton code I was given that looks like this:

def main():
    N = int(input())
    lst = [[int(i) for i in input().split()] for _ in range(N)]
    intervals = solve(N, lst)
    print_solution(intervals)
if __name__ == '__main__':
    main()

I just need to understand how to, from the terminal, input one of my test files to this script (and see the print_solution output)

CodePudding user response:

Use the fileinput module

input.txt

...input.txt contents

script.py

#!/usr/bin/python3

import fileinput


def main():
    for line in fileinput.input():
        print(line)

if __name__ == '__main__':
    main()

pipe / input examples:

$ cat input.txt | ./script.py
...input.txt contents

$ ./script.py < input.txt 
...input.txt contents

CodePudding user response:

You can take absolute or relative path in your input() function and then open this path via open()

filename = input('Please input absolute filename: ')

with open(filename, 'r') as file:
    # Do your stuff

Please let me know if I misunderstood your question.

CodePudding user response:

You can either:

A) Use sys.stdin (import sys at the top of course)

or

B) Use the ArgumentParser (from argparse import ArgumentParser) and pass the file as an argument.

Assuming A it would look something like this:

python script.py < file.extension

Then in the script it would look like:

fData = []
for line in sys.stdin.readLines():
  fData.append(line)

# manipulate fData

There are a number of ways to achieve what you want. This is what I came up with off the top of my head. It may not be the best / efficient way, but it should work. I do a lot of file I/O with python at work and this is one of the ways I've achieved it in the past.

Note: If you want to write the manipulated lines back to the file use the argparse library.

Edit:

from argparse import ArgumentParser

def parseInput():
  parser = ArgumentParser(description = "Takes input file to read")
  parser.add_argument('-f', type = str,  default = None,  required = 
  True,  help  = "File to perform I/O on")
  args = parser.parse_args()
  return args

def main():
  args = parseInput()
  fData = []
  # perform rb
  with open(args.f, 'r') as f:
    for line in f.readlines():
      fData.append(line)

  # Perform data manipulations

  # perform wb
  with open(args.f, 'w') as f:
    for line in fData:
      f.write(line)

if __name__ == "__main__":
  main()

Then on command line it would look like:

python yourScript.py -f fileToInput.extension
  • Related