0

I am new to python and working on to get input and edit a file with python. The value I want to edit is "web-iphone" with the text I get from input.

Code so far:

web = raw_input("Enter value")

The file: test.py

    local {
            value web-iphone
    }
5
  • docs.python.org/2/tutorial/… Commented Feb 21, 2015 at 11:59
  • Do I have to overwrite the file or is it possible to edit text in the file ? Commented Feb 21, 2015 at 12:00
  • Depends what you mean by edit - a file can be appended to, or parts can be replaced, it cannot be inserted to. Generally you want to over-write the file. Commented Feb 21, 2015 at 12:02
  • How can I replace the part "web-iphone" any resources I can look at ? Commented Feb 21, 2015 at 12:06
  • stackoverflow.com/questions/27123091/… lists basic ways in which you can edit a file Commented Feb 21, 2015 at 12:08

1 Answer 1

2

Edit: What you are asking is clearer now, refined my answer.

To get a file's contents:

def read_file(filename):
  return open(filename).read()

And to write to a file:

def write_file(filename, toWrite):
  file = open(filename, 'w')
  file.write(toWrite)
  file.close()

So to replace "web-iphone" with whatever the user typed in you could do:

Web = raw_input("Enter a value ")
Replaced = read_file("myfile.txt").replace("web-iphone", Web)
write_file("myfile.txt", Replaced)

For your comment:

newInput = raw_input("Enter a value ")
OldFile = read_file("myfile.txt")
value = OldFile.find("value"+6)
newFile = OldFile[:value] + newInput + OldFile[OldFile.find("\n",value+1):]
Sign up to request clarification or add additional context in comments.

8 Comments

If I dont know the value to be replaced but I know the column? As in shell - awk '{ print $2 }' is that possible ? To replace a specific column in a line ?
It is possible, I will add it to the bottom of my answer for the sake of formatting, hold on a moment please.
Since I always want "value" in that file stay, but want to change the text after value to for example web-iphone.
Oh, ok . I'll have that added to my answer in a minute.
Oops, move the +6 outside the parentheses.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.