[英]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 ? 有没有办法在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. 我用fileinput.input()
及其inplace
这样的任务,该参数。 Taking advantage of Python3.6's f-strings , here is a complete example: 利用Python3.6的f字符串 ,这是一个完整的示例:
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. 首先打开文件,并使用readlines()
读取每一行以返回内容列表。 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. 将i的值(作为字符串)添加到所需的。,通过切片覆盖现有文件并添加列表的一部分。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.