[英].txt file function read/write position
我有這個作業,我需要定義一個 function 來執行以下操作:
寫一個 function 給定一個文本文件 object 以讀寫模式打開和一個字符串,在當前讀/寫 position 的文件中插入該字符串的文本。 換句話說,function 將字符串寫入文件中,而不會覆蓋它的 rest。 退出 function 時,新的讀/寫 position 必須正好在新插入的字符串的末尾。 算法簡單; function 需要:
對於我需要做什么,我對步驟 1-4 感到非常困惑,教授也沒有幫助。
這是我做的代碼,但我不認為 function 遵循給定的參數
def readWrite(file, string):
file.read()
file.seek(0)
file.write(string)
give_file = input("enter a file name: ")
give_string = input("enter a string: ")
try:
readFile = open(give_file, "a+")
file_content = readWrite(readFile, give_string)
except FileNotFoundError:
print("File does not exist")
exit(1)
整個代碼應該要求一個簡單的.txt
文件,它將接受它和一個字符串,並將其添加到原始文件中。
例子:文件是 Twinkle.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
output:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
我找到了方法,這里是 function:
def readWrite(file, string):
if not file.readable():
print("This file is not readable")
file.close()
return
if not file.writable():
print("This file is not writable")
file.close()
return
initialPosition = file.tell()
print(initialPosition)
readContent = file.read()
file.seek(initialPosition)
file.write(string)
secondPosition = file.tell()
print(secondPosition)
file.write(readContent)
file.seek(secondPosition)
基本上,這會接收文件並將文件名和行號附加到每一行。 (行號代碼在下面的主體中)。
主體:
give_file = input("enter a file name: ")
try:
openFile = open(give_file, "r+")
position = openFile.tell()
except FileNotFoundError:
print(give_file, " does not exist or could not open")
exit(1)
counter = 0
for line in openFile:
counter += 1
openFile.seek(position)
readWrite(openFile, give_file + "\n" + "\n")
spacing = 1
while spacing <= counter:
readWrite(openFile, str(spacing) + " ")
openFile.readline()
spacing += 1
openFile.close()
那里可能有更短更優雅的解決方案,但這對我有用
我不認為我知道完整的答案,但我知道它涉及處理文件流。 為此,請TextIO
object 的 python 文檔。 根據我的經驗, save_file 中的save_file
file.write(content)
會刪除文件的現有內容。 我相信你想在底部以 append 模式打開文件,其中open
中的字符串參數是'a'
此鏈接可能會有所幫助:https://www.guru99.com/reading-and-writing-files-in-python.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.