我有一個練習,它現在很好,並且正在運行。本練習的算法是從FTP服務器下載文件並將其再次上載到FTP服務器的上傳文件夾中。 BTW這是我的代碼:具有誤導性的全球變數
import os
import zipfile
import ConfigParser
import ftputil
import shutil
import tempfile
import time
def download_files():
# Alvin: Think of a better variable name
file_list = ftp.listdir(downloads)
for filename in file_list:
# Alvin should be ftp.path.join
source = os.path.join(downloads, filename)
target = os.path.join(temp_path, filename)
ftp.download(source, target)
def zipping_files():
dirlist = os.listdir(temp_path)
global filepath
filepath = os.path.join(temp_path, 'part2b.zip')
# Alvin: find better name for zip_name
global zip_name
zip_name = zipfile.ZipFile(filepath, 'w')
# Alvin: try not to use built-in names as variable names
for list in dirlist:
# Alvin: file_path, absolute_path
get_file = os.path.join(temp_path, list)
zip_name.write(get_file, 'part2b\\' + list)
def upload_files():
ftp.upload(filepath, uploads + '/part2b.zip')
def main():
# Alvin: Do not use globals.
# Alvin: remove useless and above all misleading comments
global temp_path
temp_path = tempfile.mkdtemp()
config = ConfigParser.ConfigParser()
config.readfp(open('config.ini'))
server = config.get('main', 'Server')
username = config.get('main', 'Username')
password = config.get('main', 'Password')
global uploads
uploads = config.get('main', 'Upload folder')
global downloads
downloads = config.get('main', 'Download folder')
#connect to ftp
global ftp
# Alvin: open ftp connection when you only need it.
ftp = ftputil.FTPHost(server, username, password)
try:
download_files()
zipping_files()
upload_files()
finally:
ftp.close()
zip_name.close()
shutil.rmtree(temp_path, 'true')
print "Successfully transferred files."
print ""
print "This will close in 5 seconds. . . . ."
time.sleep(5)
if __name__ == '__main__':
main()
好吧,命名約定留給我。但是我想問一個如何重新編碼而不使用全部全局變量的例子?謝謝你的幫助!
將這些變量作爲參數傳遞。 – georg
我會嘗試一下這個建議,其實我有這個想法,但我不確定我是否會首先聲明變量?或者它可以在我的main()函數中聲明,對不起,在Python中我是新的。不管怎麼說,還是要謝謝你! – neo
在python中,你不必在賦值之前聲明變量。 –