简体   繁体   中英

write string in line 4 of text file

I need to write a constant string in many files at line 4. my text file such as :

PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "tr_en_itani" (
  "id" INTEGER  AUTO_INCREMENT,
  "sura" smallint(6) DEFAULT NULL,
  "aya" smallint(6) DEFAULT NULL,
  "aya_text" text DEFAULT NULL,
  PRIMARY KEY ("id")
);

I need to change line 4th. How I do it?

The easiest way is reading your file as a list of lines, this way:

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

now, data is a list with each one of your lines, ie

print(data[0])

will print "PRAGMA foreign_keys=OFF;",

print(data[1])

will print "BEGIN TRANSACTION;", and so on.

At this point, you can edit the fourth line this way:

data[3] = "Your new text"

And then, write back the file:

with open('yourfile.txt', 'w') as file:
    file.writelines( data )

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