나는 운동을했으며 지금은 잘되고 달리고있다. 이 실습의 골자는 FTP 서버에서 파일을 다운로드하고 FTP 서버의 업로드 폴더에 다시 업로드하는 것입니다. 이 코드는 내 코드입니다.오해의 소지가있는 전역 변수
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() 함수에서 선언되었다는 것은 괜찮은가요, 미안 해요 파이썬에서 새로운 것. 어쨌든 고마워! – neo
파이썬에서는 값을 할당하기 전에 변수를 선언 할 필요가 없습니다. –