如何写入文本文件中每一行的开头和结尾?

发布于 2024-12-12 08:17:15 字数 382 浏览 0 评论 0原文

我目前正在寻找一种方法来写入Python 中文本文件每一行的开头和结尾。

例如,

当前 TXT 文档:

Jimmy
Was
Here

将第 1 个值写入每行的开头

111Jimmy
111Was
111Here

将第 2 个值写入每行的末尾

111Jimmy222
111Was222
111Here222

可以'谷歌上似乎找不到任何描述如何正确完成此操作的内容。我找到了写入特定行的方法,但并非所有方法都以这种方式进行。

I'm currently looking for a way to write to the beginning and end of every line of a text file in Python.

For example,

Current TXT document:

Jimmy
Was
Here

Write the 1st VALUE to the beginning of every line

111Jimmy
111Was
111Here

Write the 2nd VALUE to the end of every line

111Jimmy222
111Was222
111Here222

Can't seem to find anything on Google that describes how to properly have this done. I've found methods of writing to specific lines, but not all of them in this way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

稀香 2024-12-19 08:17:15
prefix = '111'
suffix = '222'

with open('source.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))
prefix = '111'
suffix = '222'

with open('source.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))
知你几分 2024-12-19 08:17:15

您可以使用 fileinputinplace=1

import fileinput
for line in fileinput.input('test.txt', inplace=1):
    print '{0}{1}{2}'.format('111', line.rstrip('\n'), '222')

You can make changes to the file without opening multiple files by using fileinput with inplace=1:

import fileinput
for line in fileinput.input('test.txt', inplace=1):
    print '{0}{1}{2}'.format('111', line.rstrip('\n'), '222')
情归归情 2024-12-19 08:17:15

假设您已经使用列表中的 readlines() 读取了文件,您可以执行以下操作

value1 = "" # appended at first
value2 = "" # appended at last
data = file.readlines()
data = [ ( value1 + str.rstrip('\n') + value2 + "\n" ) for str in data ]

,然后将数据写回文件......

Assuming you have read the file using readlines() in a list you can do

value1 = "" # appended at first
value2 = "" # appended at last
data = file.readlines()
data = [ ( value1 + str.rstrip('\n') + value2 + "\n" ) for str in data ]

and then write data back to the file....

心头的小情儿 2024-12-19 08:17:15
f1o = open("input.txt", "r")
f2o = open("output.txt", "w")

for line in f1o:
    f2o.write("111%s222\n" % line.replace("\n"))

f1o.close()
f2o.close()
f1o = open("input.txt", "r")
f2o = open("output.txt", "w")

for line in f1o:
    f2o.write("111%s222\n" % line.replace("\n"))

f1o.close()
f2o.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文