【问题标题】:how to write into text file using command line argument in Python如何在 Python 中使用命令行参数写入文本文件
【发布时间】:2020-04-18 22:29:04
【问题描述】:

, 当我尝试在我的 Python 中编写程序时遇到问题。这是我的要求: 1) 接受输入(它是一个 csv 文件)作为命令行参数 2) 读取这个 csv 文件 3) 计算这个 csv 文件中的单词和字符数 4)并将结果 - csv文件的单词和字符数写入另一个文本文件 - 说results.txt

这是我试过的”

  import sys
  print('the version of python')
  print(sys.version)


  with open(sys.argv[1], 'rt') as f, open(sys.argv[2],'r') as fw:
  contents = f.read()
  words= contents.split()
  print(' displaying words in txt file..', words)
  print(' number of words in txt file..', len(words))

  contents1 = fw.read()
  words1= contents1.split()
  print(' displaying words in txt file..', words1)
  print(' number of words in txt file..', len(words1))

我没有得到结果。第一部分,从 csv 读取文件现在工作正常。 但是,如何写入 results.txt 文件?

【问题讨论】:

  • 你为什么要计算第二个文件的字数?或者是否有两个文件来计算单词,在哪种情况下要写入哪个文件?
  • 在上面的代码中,我只是尝试进行测试。我需要展示的是,获取输入文件的字数、字符数并将其写入另一个 results.txt 文件
  • Austin,不,只有一个文件需要统计,即第一个输入文件,该输入文件的字数和字符数应写入新创建的 results.txt file..我可以创建一个新的文本文件吗,如果我将 Results.txt 文件作为第二个命令行参数以及什么代码,我需要编写以便在 Python 中创建一个新的文本文件。

标签: python-3.x command-line-arguments file-handling


【解决方案1】:

要写入文件,您需要以“w”模式打开它,然后使用.write() 函数写入内容。像这样的:

file1 = open("myfile.txt","w") 
file1.write("Number of words: {}".format(len(words))
file1.close()

希望对你有帮助!

【讨论】:

  • - @ghanasyam - ,在我的代码中,我使用了关键字,所以,我该如何修改你的代码,以便写入新的 results.txt 文件
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 2018-10-14
  • 2014-10-19
  • 1970-01-01
  • 2014-06-07
  • 2020-02-29
  • 2017-01-01
  • 1970-01-01
相关资源
最近更新 更多