Python User Input Within Shell

时间:2016-04-04 18:41:08

标签: python

I'm sure this has been asked before, but I wasn't even sure how to phrase the question to get proper results back from a search engine.

Anyway, I need to create a Python script that uses a text file as input.

Within a Linux shell, a user can type python samplescript.py NewUser.txt - The script (samplescript.py) will then use "NewUser.txt" as input.

My question is, how do I code the script so that it uses "NewUser.txt" or another file as the input. Do I use raw_input()?

I realize this is probably a novice question but I am rather new to Python so any help is appreciated. Thank you all!

3 个答案:

答案 0 :(得分:0)

The basics would be something like the following:

import sys
file_path = sys.argv[1]

with open(file_path,"r") as f:
    for line in f:
        print(line)

Line by line:

  1. Import sys
  2. Get the file path from the FIRST argument.
  3. Open the file for reading
  4. Iterate and print the data.

答案 1 :(得分:0)

Arguments passed to the python script are inside sys.argv. The first argument is always the filename of the python script. Additional arguments come after that. So in your example, you would get the filename NewUser.txt by

import sys

filename = sys.argv[1]

You can then open the file, read the contents, and pass that as input to the rest of your script. This assumes your passing the whole filepath and not just the name of the file, which would only work if your current working directory was the same as the directory of the file you're reading in.

with open(filename, 'r') as f:
    txt = f.read()

答案 2 :(得分:0)

我认为您要做的是使用raw_input从文件中获取输入。

程序使用stdin / stdout进行输入/输出。您可以使用箭头进行重定向:>将输出重定向到文件,<重定向文件输入。

一般情况下我们使用:

command < input-file

,在你的情况下:

python samplescript.py < NewUser.txt

现在,当您使用raw_input时,将从NewUser.txt

中读取输入内容