hi every one this is my first q can someone pleas help whit this. I am trying to learn python on my own and i got stuck with the command line argument. can someone please break it down to me >> use anyfile.text and sys.argv[1] how to open the file and go through the lines how to split and change or replace some words. please step by step thank you
Asked
Active
Viewed 28 times
-1
-
Does this answer your question? [Calling an external command from Python](https://stackoverflow.com/questions/89228/calling-an-external-command-from-python) – Philip Ciunkiewicz Apr 02 '20 at 22:38
-
Hi rafi, and welcome to Stack Overflow! Stack Overflow is designed for asking specific questions, rather than open-ended questions like yours. You may like to look into the many available online resources such as free tutorials to help you learn the different steps that you're asking (using command line arguments, opening files, parsing, splitting, and replacing strings) and if you get stuck with a specific issue, come back and ask how to solve your specific problem, while showing us your attempt to solve the problem. – Oliver.R Apr 02 '20 at 22:42
-
Oliver.R thank you Oliver for your words and replying .. – rafi Apr 02 '20 at 22:58
1 Answers
0
I think you need to add more details but if you want something like:
python my_code.py name_of_file.txt
Your code will look like this:
import sys
# This is used to avoid your code runs when is called by another python file,
# In this case, is not necessary, but it is a good practice
if __name__ == "__main__":
# To open a file
file = open(sys.argv[1], "r")
new_file = open("new_file.txt", "w") # in case you want to save your changes in a new fil
line = file.readline()
# Stops when readline() is null
while(line):
parse_line = line.split(" ") # this will split the line in an array of
# word, where words are identified by space character
line_replaced = line.replace("bad word", "good word") # this replace every bad word for goodword
new_file.write("{}\n".format(line_replaced)) # to write as new line
file.close()
new_file.close()
Hope this is all you need.

Juan Ma
- 34
- 3