简体   繁体   中英

How can I save the first line of a file?

I would like to know how to save the first line of a file using python, but all the time it ends up deleting the first lines and scrolling over the top.

newfile = open('news.php', 'r+');
newfile.write('Texto');
newfile.close();

If you want to add to the top of the file (pushing the top line down):

with open("news.php", "r") as f:
    content = f.readlines()

# insert the desired top line at index 0, either directly or with a variable
content.insert(0, some_new_first_line)

with open("news.php", "w") as f:
    content = "".join(content)
    f.write(content)

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