使用 python 写入文件并保存到 ftp 2.6

Write to file and save to ftp with python 2.6

我正在尝试存储我在 ftp 服务器上创建的文件。

我已经能够创建临时文件并将其存储为一个空文件,但我无法在存储之前向该文件写入任何数据。 这是部分工作的代码:

#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()

我做错了什么?

谢谢

求!

要知道在文件(或类文件对象)中读取或写入的位置,Python 保留指向文件中某个位置的指针。文档简单地将其称为 "the file's current position"。因此,如果您的文件中包含这些行:

hello world
how are you

您可以像下面的代码一样用Python阅读它。请注意,tell() 函数会告诉您文件的位置。

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

Python现在是十二个字符"into"的文件。如果你计算字符数,那就意味着它就在换行符之后(\n 是单个字符)。使用 readlines() 或任何其他读取函数继续从文件中读取将使用此位置来知道从哪里开始读取。

写入文件也会使用并增加位置。这意味着如果在写入文件后从文件中读取,Python 将从它保存的位置开始读取(就在您刚刚写入的内容之后),而不是文件的开头。

ftp.storlines() 函数使用相同的 readlines() 函数,它只从文件的位置开始读取,所以无论你写什么。您可以通过在调用 ftp.storlines() 之前返回文件的开头来解决此问题。使用 f.seek(0) 将文件位置重置为文件的开头。