在Python中写入文件的实际位置 [英] Writing in file's actual position in Python

查看:117
本文介绍了在Python中写入文件的实际位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取文件中的一行并将新行("\ n")字符插入一行的n位置,以便将9个字符的行转换为3个3个字符的行行,像这样:

I want to read a line in a file and insert the new line ("\n") character in the n position on a line, so that a 9-character line, for instance, gets converted into three 3-character lines, like this:

"123456789" (before)
"123\n456\n789" (after)

我已经尝试过了:

f = open(file, "r+")
f.write("123456789")
f.seek(3, 0)
f.write("\n")
f.seek(0)
f.read()

->'123 \ n56789'

-> '123\n56789'

我希望它不替换位置n中的字符,而只是在该位置插入另一个("\ n")字符.

I want it not to substitute the character in position n, but only to insert another ("\n") char in that position.

关于如何执行此操作的任何想法? 谢谢

Any idea about how to do this? Thanks

推荐答案

我认为您尝试使用的方法没有任何办法:您必须从文件中读取文件的末尾您要插入的位置,然后在您希望的位置写入新字符,然后在其后写回原始数据.这与C语言或带有seek()类型API的任何语言中的工作方式都是相同的.

I don't think there is any way to do that in the way you are trying to: you would have to read in to the end of the file from the position you want to insert, then write your new character at the position you wish it to be, then write the original data back after it. This is the same way things would work in C or any language with a seek() type API.

或者,将文件读取为字符串,然后使用列表方法插入数据.

Alternatively, read the file into a string, then use list methods to insert your data.

source_file = open("myfile", "r")
file_data = list(source_file.read())
source_file.close()
file_data.insert(position, data)
open("myfile", "wb").write(file_data)

这篇关于在Python中写入文件的实际位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆