相关疑难解决方法(0)

如何使用open with语句打开文件

我正在研究如何在Python中进行文件输入和输出.我编写了以下代码来读取文件中的名称列表(每行一个)到另一个文件,同时根据文件中的名称检查名称,并将文本附加到文件中的出现位置.代码有效.可以做得更好吗?

我想对with open(...输入和输出文件使用该语句,但无法看到它们在同一块中的含义,这意味着我需要将名称存储在临时位置.

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    outfile = open(newfile, 'w')
    with open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

    outfile.close()
    return # …
Run Code Online (Sandbox Code Playgroud)

python io file-io file python-3.x

184
推荐指数
3
解决办法
53万
查看次数

ftp.retrbinary()帮助python

我创建了一个python脚本来连接到remserver.

datfile = []
for dk in range(len(files)):
  dfnt=files[dk]
  dpst=dfnt.find('.dat')
  if dpst == 15:
    dlist = dfnt[:]
    datfile.append(dlist)

    assert datfile == ['a.dat','b.dat']
    # True
Run Code Online (Sandbox Code Playgroud)

如你所见,创建一个列表.现在我将此列表传递给

ftp.retrbinary('datfile')
Run Code Online (Sandbox Code Playgroud)

但是这一行会返回一个错误:

typeerror: retrbinary() takes at least 3 arguments (2 given)
Run Code Online (Sandbox Code Playgroud)

不知道在找什么?

python ftp binary ascii

9
推荐指数
1
解决办法
3万
查看次数

Python ftplib损坏文件?

我正在使用ftplib在Python中下载文件,直到最近一切似乎都工作正常。我正在这样下载文件:

ftpSession = ftplib.FTP(host,username,password)
ftpSession.cwd('rlmfiles')
ftpFileList = filter(lambda x: 'PEDI' in x, ftpSession.nlst())
ftpFileList.sort() 
for f in ftpFileList:
    tempFile = open(os.path.join(localDirectory,f),'wb')
    ftpSession.retrbinary('RETR '+f,tempFile.write)
    tempFile.close()
ftpSession.quit()
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

直到最近,它仍按预期下载了我需要的文件。但是,现在,我正在下载的“我的文件”已损坏,仅包含一长串垃圾ASCII。我知道不是将文件发布到FTP上,因为我也有一个Perl脚本可以从同一FTP成功完成此操作。

如果还有其他信息,这是调试器在下载文件时在命令提示符下显示的内容:

在此处输入图片说明

是否有人retrbinary()在Python的ftplib中使用损坏的文件内容遇到任何问题?

我真的很困/沮丧,并且在这里没有遇到与可能的腐败相关的任何事情。任何帮助表示赞赏。

python ftp corruption

5
推荐指数
1
解决办法
635
查看次数

标签 统计

python ×3

ftp ×2

ascii ×1

binary ×1

corruption ×1

file ×1

file-io ×1

io ×1

python-3.x ×1