简体   繁体   中英

Write to file and save to ftp with python 2.6

I'm trying to store a file I create on an ftp server.

I've been able to create the temp file and store it as an empty file, but I haven't been able to write any data to the file before storing it. Here is the partially working code:

#Loggin to server.
ftp = FTP(Integrate.ftp_site)       
ftp.login(paths[0], paths[1])
ftp.cwd(paths[3])

f = tempfile.SpooledTemporaryFile()

# Throws error.
f.write(bytes("hello", 'UTF-8'))

#No error, doesn't work.
#f.write("hello")

#Also, doesn't throw error, and doesn't write anything to the file.
# f.write("hello".encode('UTF-8'))

file_name = "test.txt" 
ftp.storlines("Stor " + file_name, f)

#Done.                
f.close()    
ftp.quit()

What am I doing wrong?

Thanks

Seeking!

To know where to read or write in the file (or file-like object), Python keeps a pointer to a location in the file. The documentation simply calls it "the file's current position". So, if you have a filed with these lines in it:

hello world
how are you

You can read it with Python like in the following code. Note that the tell() function tells you the file's position.

>>> f = open('file.txt', 'r')
>>> f.tell()
0
>>> f.readline()
'hello world\n'
>>> f.tell()
12

Python is now twelve characters "into" the file. If you'd count the characters, that means it's right after the newline character ( \\n is a single character). Continuing to read from the file with readlines() or any other reading function will use this position to know where to start reading.

Writing to the file will also use and increment the position. This means that if, after writing to the file you read from the file, Python will start reading at the position it has saved (which is right after whatever you just wrote), not the beginning of the file.

The ftp.storlines() function uses the same readlines() function, which only starts reading at the file's position, so after whatever you wrote. You can solve this by seeking back to the start of the file before calling ftp.storlines() . Use f.seek(0) to reset the file position to the very start of the file.

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