python输出到文本文件

时间:2017-08-02 12:51:42

标签: python formatting tabular

我需要将我从代码中计算出的值输出到某种格式的文本文件中。首先,我将解释我的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

屏幕上的所有输出都是由于我使用代码计算的变量值的print语句。你能帮我解决一下这个问题吗?

5 个答案:

答案 0 :(得分: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']]

“output.txt的”:

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

答案 1 :(得分:0)

如果您的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)

答案 2 :(得分:0)

如果您的print语句正是按照您想要的方式创建输出,我强烈建议您使用new-ish 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

答案 3 :(得分:0)

您可以使用numpy.savetxt并使用header-keyword

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

答案 4 :(得分:0)

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