簡體   English   中英

我無法讀取我剛剛在 python 中寫入的文件

[英]I can't read the file i just write in python

我寫了一個腳本,把每個數據前后的空格去掉,比如1,2,3,4會變成1,2,3,4。 我的代碼是成功的,object文件是真的(在電腦上打開,結果完全正確)。 之后,我做了一個測試,在這個測試中,我嘗試通過 python 讀取 object 文件,結果是無。 我不知道為什么。 這是我下面的代碼

with open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\data.csv","r+") as fi,\        open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\clear_data.csv","w+") as fo:
    fi_reader=fi.readlines()  
    for line in fi_reader:
        line=line.replace(" ","")
        fo.write(line)  
    #Here's where things start to go wrong
    fo_reader=fo.read()
    print("the result of fo is here:",fo_reader)

原始文件

1,2,3,4,5,6,7
8, 3, 2, 7, 1, 4, 6, 5
6, 1, 3, 8, 5, 7, 4, 2
'a','b','c','x','y','z','i','j','k'
'k', 'b', 'j', 'c', 'i', 'y', 'z', 'a', 'x'
'z', 'c', 'b', 'a', 'k', 'i', 'j', 'y', 'x'
'a', 'y', 'b', 'x', 'z', 'c', 'i', 'j', 'k'
5, 2, 4, 7, 1, 6, 8, 3

我的 object 文件完全正確

1,2,3,4,5,6,7
8,3,2,7,1,4,6,5
6,1,3,8,5,7,4,2
'a','b','c','x','y','z','i','j','k'
'k','b','j','c','i','y','z','a','x'
'z','c','b','a','k','i','j','y','x'
'a','y','b','x','z','c','i','j','k'
5,2,4,7,1,6,8,3

但是打印是錯誤的

the result of fo is here:  (There should have some result, but it's nothing)

嘗試關閉並重新打開文件或使用 seek 移動到文件的前面。 我假設 python 正在嘗試從當前的 Cursor position 中讀取,這將是它完成寫入的地方。

查看 python 文檔中的第 7.2.1 節文件對象的方法: Python 7.2.1 文件對象的方法

您已授予一個文件的讀取權限,而另一個文件具有寫入權限,因此您無法寫入然后讀取 fo 文件,例如我已授予 MyFile_1.txt 文件的讀取權限

with open("MyFile_1.txt","r") as ReadText:
   print(ReadText.read()) # This is Working
   ReadText.write("My Blabla"); # Not Working Because I only gave him readability "r+" or "r"

無論如何,您的代碼將是這樣的

with open("C:/Users/Root/Desktop/1.txt","r+") as fo:
fi_reader=fo.readlines()
with open("C:/Users/Root/Desktop/2.txt","w+") as fi:
    for line in fi_reader:
        fi.write(line.replace(" ",""))

使用 open("C:/Users/Root/Desktop/2.txt","w+") 作為 fi: print(fo.read())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM