简体   繁体   中英

How do you add characters to a line in python in an existing text file?

Suppose i have the text file:

apple  
banana  
fruit  

how would i get that to :

1.apple  
2.banana  
3.fruit   

Is there a way to do this in python ?

myfile=open("dates.txt","a")
   for i in range(14):
myfile.write(i)
   myfile.write("\n")

I use fileinput.input() and its inplace parameter for tasks such as this. Taking advantage of Python3.6's f-strings , here is a complete example:

import fileinput

for i, line in enumerate(fileinput.input(inplace=True), 1):
    print(f'{i}.{line.rstrip()}')

Sample usage:

$ cat groceries.txt 
apple
banana
fruit
$ python3 numberize.py groceries.txt 
$ cat groceries.txt 
1.apple
2.banana
3.fruit
$ 

First open your file and read each line with readlines() to return a list of the contnse. Then initerate through your list giving a variable the number you wish to give it. Add the value of i (as a string) to the desired ., write over your existing file adding part of the list by slicing.

with open('first.txt') as pri:
    a = pri.splitlines() 
for i in range(1, len(a)+1):

    part = str(i) + '.'

    with open('first.txt', 'w') as file:
        file.write(part + a[i-1])

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