简体   繁体   中英

How to read file from the command line on Mac terminal for Python

How would I read a file (.in format) and apply it to my.py Python program?

For example, my python code is titled as Add_4.py :

import sys
main():
    num = int(sys.stdin.readline().strip())
    final_output = num + 4
    print(final_output)
if __name__ == "__main__":
    main()

And the text file would be titled Numbers.in :

5
18
-3

I believe I have to use the '<' symbol within the terminal, and I know that I have to trace the location of my files, but I am brand new to Python and Coding in general so I am having a hard time figuring this out. This format is being used for my class btw. Sorry if anything is confusing.

Let's say you have file add4.py , content:

import sys
def main():
    num = int(sys.stdin.readline().strip())
    final_output = num + 4
    print(final_output)
if __name__ == "__main__":
    main()

and you have plaintext file Numbers.in , content:

5
18
-3

You can pipe OR redirect content of Numbers.in to add4.py by using | (pipe) or by using < (read stdin from file)

example 1:

$ cat Numbers.in | python add4.py
9

example 2:

$ python add4.py < Numbers.in
9

Do note that because of the way your python code is written, only first line is read (number 5 ) and then added with 4 to become 9 .


If you want to read multiple lines and expect output like

9
22
1

then you should use readlines rather than readline .

File add4all.py , content:

import sys
def main():
    lines = sys.stdin.readlines()
    for num in lines:
        final_output = int(num) + 4
        print(final_output)
if __name__ == "__main__":
    main()

Then the result is:

$ python add4all.py < Numbers.in 
9
22
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM