除非我们讨论的是一种相当人为的情况,即您已经对该文件了解很多,否则答案是否定的。您必须迭代文件以确定换行符在哪里;当涉及到文件存储时,“行”没有什么特别之处——看起来都是一样的。
这应该有效 -
f = open(r'full_path_to_your_file', 'r') # pass an appropriate path of the required file
lines = f.readlines()
lines[n-1] = "your new text for this line" # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
f.close() # close the file and reopen in write mode to enable writing to file; you can also open in append mode and use "seek", but you will have some unwanted old data if the new data is shorter in length.
f = open(r'full_path_to_your_file', 'w')
f.writelines(lines)
# do the remaining operations on the file
f.close()
Run Code Online (Sandbox Code Playgroud)
但是,如果文件大小太大,这可能会消耗资源(时间和内存),因为该f.readlines()函数会加载整个文件,并在列表中分成行。
这对于中小型文件来说就很好了。