0

I have this script:

f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
    if a ==58:
         print (line)
         line1 = "google.ca"
         f.write(line1)
         print line
    a = a+1
f.close()

I want to keep my file but only to change what is written on line 58 to "google.ca" then save it using linux: mint-17.2

4 Answers 4

1
# Read data from file
with open('yourfile.txt', 'r') as file:
    # read all line in the file to data array
    data = file.readlines()

# change data on line 58 (array start from 0) 
data[57] = 'Data you need to change'

# Write data back 
with open('yourfile.txt', 'w') as file:
    file.writelines(data)
Sign up to request clarification or add additional context in comments.

1 Comment

I provided the full script in the answer section
0

You need to decide whether you want to write a new file (with print) or change the old file (with r+ mode and f.write). You will probably be happiest if you write a new file.

Comments

0
dataRead = []
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
    if a == 58:
       line = "google.ca"
    dataRead.append(line)
    a = a+1
f.close()

f2 = open("/some/new/file","w")
for line in dataRead:
    f2.write(line)
f2.close()

Comments

0

With the answer of Adisak Anusornsrirung I wrote it like this:

with open('sss.txt','r') as file:
data = file.readlines()

print (data[14])
file.close()
data[14] = "some data here"+"\n"
with open ("sss.txt", 'w') as file:
    file.writelines(data)
file.close()
f = open("sss.txt", 'r')
print (f.read())
f.close()

Comments

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.