如何在python3中向文本文件中读取的字符串添加字符串?

2024-09-30 03:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典文本文件,我想给每个单词添加一个字符串,比如"http://" + word + ".com" 我试过这个:

      f = open('esp.txt', 'r')
      urls = open('urls.txt', 'w')
      while True:
          nline = 1
          contentCOM = 'http://www.' + f.readlines(nline) + '.com'
          contentCOM.write(urls)
          nline = nline + 1

但它给了我以下错误:TypeError: Must be str, not list


Tags: 字符串txtcomtruehttp字典open单词
2条回答

如果你所有的“话”都在一行又一行esp.txt文件,然后可以这样迭代:

f = open('esp.txt', 'r')
urls = open('urls.txt', 'w')
for lines in f:
    urls.write('http://www.' + lines + '.com' + '\n')

f.close()
urls.close()

看起来您使用的是readlines()与单数readline()

https://docs.python.org/3.7/tutorial/inputoutput.html#methods-of-file-objects

提示是,如果您查看错误和行号,您会注意到这里得到的是一个列表而不是一个字符串:

contentCOM = 'http://www.' + f.readlines(nline) + '.com'

最好检查Python文档并查看readlines()的输出,看看输出是什么。然后,您将把列表输出放在一起,说明是您的错误,并将查找一个新函数。你知道吗

相关问题 更多 >

    热门问题