【问题标题】:python output to a text filepython输出到文本文件
【发布时间】:2017-08-02 12:51:42
【问题描述】:

我需要将我从代码中计算出的值以某种格式输出到文本文件中。首先,我将解释我从 python 代码输出的样子,然后解释我想要文本文件的样子。

Column A
1
2
3
4
Column B
3
4
1
9
Column C
20
56
89
54

我想要的文本文件如下

Number    Column A    Column B     Column C
0         1           3            20
1         2           4            56
2         3           1            89
3         4           9            54

屏幕上的所有输出都是由于我使用代码计算的变量值的打印语句。你能帮我看看我该怎么做吗?

【问题讨论】:

  • 向我们展示您自己尝试了什么以及您的问题是什么。
  • @IrmendeJong 的意思是:发布您的代码。
  • 尝试打印第一行。
  • 我的代码有 200 行。可以贴吗?
  • 也许您可以将其添加到 gist 并分享链接:gist.github.com

标签: python formatting tabular


【解决方案1】:

如果项目按此顺序出现,您必须将其保存到列表、字典或其他内容中,然后打印。看这个例子:

output = [[] for i in range(5)] # [[],[],[],[],[]]

for ind, item in enumerate(["Column A","1","2","3","4"]):
    print(item)
    output[ind].append(item)    

for ind, item in enumerate(["Column B","3","4","1","9"]):
    print(item)
    output[ind].append(item)

with open("output.txt", "w") as f:
    for row in output:
        f.write('\t'.join(row))
        f.write('\n')

打印:

Column A
1
2
3
4
Column B
3
4
1
9

输出:

[['Column A', 'Column B'], ['1', '3'], ['2', '4'], ['3', '1'], ['4', '9']]

“输出.txt”:

Column A    Column B
1   3
2   4
3   1
4   9

【讨论】:

    【解决方案2】:

    如果您有一个 print() 语句已经完全符合您的要求,那么您只需将输出重定向到一个文本文件。

    with open(r'path_to\my_file.txt','w') as textfile:
        ... your existing code goes here ...
        ...
        print ( ... whatever your print statement does ..., file=textfile)
    

    【讨论】:

      【解决方案3】:

      如果您的 print 语句完全按照您想要的方式创建该输出,我强烈建议使用新的 pathlib module(在 Python >= 3.4 中可用)来创建您的文件。它非常适合处理类似路径的对象(Windows 和其他操作系统)。

      如果您的文件内容以字符串形式存储在data 中,您可以这样做:

      from pathlib import Path
      
      file_path = Path('some_file.txt') # a relative file path - points within current directory
      file_path.write_text(data) # overwrites existing file of same name
      file_path.write_text(data, mode='a') # appends to an existing file of same name 
      

      这里有一个小Path 教程。

      It's Paths - Paths all the way down

      为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,可以是绝对路径对象相对路径对象

      一些有用的路径的简单显示-例如当前工作目录和用户主目录-如下所示:

      from pathlib import Path
      
      # Current directory (relative):
      cwd = Path() # or Path('.')
      print(cwd)
      
      # Current directory (absolute):
      cwd = Path.cwd()
      print(cwd)
      
      # User home directory:
      home = Path.home()
      print(home)
      
      # Something inside the current directory
      file_path = Path('some_file.txt') # relative path; or 
      file_path = Path()/'some_file.txt' # also relative path
      file_path = Path().resolve()/Path('some_file.txt') # absolute path
      print(file_path)
      

      要向下导航文件树,您可以执行以下操作。请注意,第一个对象 homePath,其余的只是字符串:

      file_path = home/'Documents'/'project'/'data.txt' # or
      file_path = home.join('Documents', 'project', 'data.txt')
      

      要读取位于某个路径的文件,您可以使用其open 方法而不是open 函数:

      with file_path.open() as f:
          dostuff(f)
      

      但您也可以直接抓取文本!

      contents = file_path.read_text()
      content_lines = contents.split('\n')
      

      ...直接写文本!

      data = '\n'.join(content_lines)
      file_path.write_text(data) # overwrites existing file
      

      以这种方式检查它是文件还是目录(并且存在):

      file_path.is_dir() # False
      file_path.is_file() # True
      

      创建一个新的空文件,不要像这样打开它(默默地替换任何现有文件):

      file_path.touch()
      

      要使文件仅在文件不存在的情况下,请使用exist_ok=False

      try:
          file_path.touch(exist_ok=False)
      except FileExistsError:
          # file exists
      

      像这样创建一个新目录(在当前目录下,Path()):

      Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
      Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
      Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
      

      以这种方式获取路径的文件扩展名或文件名:

      file_path.suffix # empty string if no extension
      file_path.stem # note: works on directories too
      

      name 用于路径的整个最后一部分(如果存在的话,则使用词干和扩展名):

      file_path.name # note: works on directories too
      

      使用with_name 方法重命名文件(该方法返回相同的路径对象但具有新的文件名):

      new_path = file_path.with_name('data.txt')
      

      您可以像这样使用iterdir 遍历目录中的所有“东西”:

      all_the_things = list(Path().iterdir()) # returns a list of Path objects
      

      【讨论】:

      • 虽然这很有趣,但它与解决问题中的问题并不真正相关。
      • @mkrieger1 我不同意。 OP 想知道如何将数据写入文件。这是我展示如何做的第一件事。我在这里的意图是“出售” OP 使用 pathlib 模块来解决未来的问题,因为它很棒并且会为 OP 省去很多麻烦。 pathlib 还是相当新的,大多数人似乎并不知道它。
      【解决方案4】:

      我搜索并发现最好在终端中打印值,就像我在文本文件中想要的那样。所以我重写了我的代码以将值显示为一个完整的选项卡限制行并且它有效。我感谢您的所有帮助。 我不确定这是否可以标记为答案。如果不让我知道,我会添加为评论。

      【讨论】:

        【解决方案5】:

        您可以使用numpy.savetxt 并使用标题关键字

        https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多