2

Python の ftplib モジュールを使用して、csv ファイルを ftp サーバーに保存しようとしています。現在、2 次元配列で天気値の確率を生成する約 30 行のコードがあります。次に、この 2 次元配列を csv ファイルに書き込みます。

csv ファイルをローカル ドライブに書き込むと、Excel 内で期待どおりにファイルが表示されます。ただし、ファイルを ftp サーバーにアップロードした後にファイルを表示すると、すべての行の後に改行文字が追加されていることがわかります。

問題が何であるかを確認するためにいくつかの小さなテストを行ったところ、coreftp を使用して csv ファイルをアップロードできました。それを行った後、csvファイルは正しく表示されます。したがって、ファイルは問題ないと確信しています。これは、Pythonがファイルをftpサーバーにアップロードするときに発生するものです。

私は元々、拡張子が .csv のテキスト ファイルを作成し、それをバイナリ ファイルとして再度開いてアップロードしていました。それが問題かもしれないと思ったので、 csv モジュールを使用してみましたが、同じ問題です。

これが現時点での私のコードです...

TEMPSHEADER = [i-50 for i in range(181)]#upper bounds exclusive
WINDSHEADER = [i for i in range(101)]#upper bounds exclusive
HEADER = TEMPSHEADER + WINDSHEADER
for site in ensmosdic:
    ensmos = ensmosdic.get(site)
    with open(utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.csv","w",newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=",")
        writer.writerow(["CODE        ","F","ForecastDate","HOUR"]+HEADER)
        siteTable =[[0 for x in range(286)] for y in range(24,169)]#upper bounds exclusive
        ###########
        #other code here, but not important with regards to post
        ###########
        for i in siteTable:
            writer.writerow(i)

        csvfile.close()#not sure if you have to close csv file, not in csv module docs
    f = open(utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.csv","rb")
    ftpInno.storbinary("STOR " + utcnow.strftime("%Y-%m-%d-") + site +"-prob.csv",f)
    f.close()
ftpInno.close()

前もって感謝します

4

2 に答える 2

0

これにより、問題が明らかになる可能性があります。WindowsコマンドラインとWindows PowerShellを使用して、ftp getおよびmgetコマンドで.csvファイルを転送するプロジェクトがありました。そして、あなたが言ったように、私は各行の間に余分なものを得ていました. バイナリ転送モードに切り替えると、問題が解決したようです。たとえば、ftp ダイアログに入ったら、「binary」と入力して Enter キーを押すだけで、モードが切り替わります。ここに画像の説明を入力

于 2020-10-03T15:48:07.953 に答える
0

After an hour or so of trouble shooting, the answer is fairly simple, although I am not entirely sure why it works.

what i did was create a text file instead of a csv file which I was doing in my original question

with open(FILELOCATION + utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.txt","w") as f:
    #write to the file below
    f.close()
#open file again as a txt file
f = open(FILELOCATION + utcnow.strftime("%Y-%m-%d") + "-" +site+"-prob.txt","rb")
ftp.storlines("STOR " + utcnow.strftime("%Y-%m-%d-") + site +"-prob.csv",f)
f.close()

reading the file as a binary file and then storing it with the storlines method removed the extra lines I was seeing within the file after I uploaded it to an ftp server.

于 2013-10-09T01:00:42.780 に答える