简体   繁体   中英

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

I write a script to remove spaces before and after each data, such as 1,2, 3, 4 will become 1,2,3,4. My code is successful,the object file is true(By opening it on the computer, the result is completely correct). After it, I did a test,in this test,I try to read the object file by python,the result is none. I don't know why. Here is my code below

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)

Origin file

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

My object file is entirely right

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

But the print is an error

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

Try closing and reopening the file or use seek to move to the front of the file. I would assume python is trying to read from the current Cursor position which would be where it finished writing.

Check out Section 7.2.1 Method of File Objects in the python documentation: Python 7.2.1 Methods of File Objects

You have given read permission to one file and the other file has write permission so you can't write and then read the fo file for example I have given read permission to the MyFile_1.txt file

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"

Anyway your code will be something like this

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(" ",""))

with open("C:/Users/Root/Desktop/2.txt","w+") as fi: print(fo.read())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM