简体   繁体   English

如何在现有文本文件的python中的行中添加字符?

[英]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.

相关问题 如何使用 Python 更改现有文本文件以在特定行之后添加新数据 - How do I alter an existing text file to add new data after a specific line using Python 如何在python中将列添加到现有文本文件中? - How do i add a column to an existing text file in python? 如何在 Python 中的特定行中访问文本文件中的数据? - How do you access data in a text file in a specific line in Python? 你如何在Python中阅读文本文件的特定行? - How do you read a specific line of a text file in Python? 如何使用 python 从一行中剪切文本并将 append 剪切到文本文件中的另一行? - How do you cut text from a line and append it to another line in text file using python? 如何使用Python向现有的PDF文件添加文本 - How to add text to existing PDF file with Python 在Python中,如何读取特定行上的特定字符 - In Python, how do you read specific characters on a specific line 如何将文件中的多行文本转换为python中的一行文本? - How do you turn multiple lines of text in a file into one line of text in python? 你如何从文本文件python中删除最大数字的行? - how do you delete the line with the biggest number from a text file python? Python-如何为while循环的迭代在文本文件中写新行? - Python - How do you write a new line in a text file for ever iteration of a while loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM