简体   繁体   English

如何将输出保存为.txt文件?

[英]How to save the output as a .txt file?

I want to save the output as a text file on my system. 我想将输出保存为我的系统上的文本文件。 The name of the output file should get from the user in command prompt. 输出文件的名称应该在命令提示符下从用户处获得。

   output = input("Enter a name for output file:")    

   my_file = open('/output.txt', "w") 

    for i in range(1, 10):
       my_file.write(i)

Is this correct way of doing?? 这是正确的做法吗?

Do like this 这样做

output = raw_input("Enter a name for output file:")    
my_file = open(output + '.txt', "w") 
for i in range(1, 10):
    my_file.write(str(i))

You can do the following: 您可以执行以下操作:

import os

# you can use input() if it's python 3
output = raw_input("Enter a name for output file:")

with open("{}\{}.txt".format(os.path.dirname(os.path.abspath(__file__)), output), "w") as my_file:
    for i in range(1, 10):
        my_file.write("".format(i))

At this example we are using the local path by using os.path.dirname(os.path.abspath(__file__)) we will get the current path and we will add it output.txt 在这个例子中,我们使用os.path.dirname(os.path.abspath(__file__))来使用本地路径。我们将获取当前路径,我们将添加它output.txt

  1. To read more about abspath() look here 要了解有关abspath()更多信息, abspath()查看此处

  2. To read more about with look here 阅读更多关于这里的内容

  3. write method in you case will raise a TypeError since i needs to be a string 在你的情况下write方法将引发TypeError,因为i需要是一个string

So couple of changes I made. 所以我做了几个改变。 You need to do something like: 你需要做一些事情:

    output + '.txt'

to use the variable output as the file name. 使用变量输出作为文件名。

Apart from that, you need to convert the integer i to a string by calling the str() function: 除此之外,您需要通过调用str()函数将整数i转换为字符串:

    str(i)

becuase the write function only takes strings as input. 因为write函数只接受字符串作为输入。

Here is the code all together: 以下是所有代码:

    output = raw_input("Enter a name for output file: ")    

    my_file = open(output + '.txt', 'wb') 

    for i in range(1, 10):
        my_file.write(str(i))

    my_file.close()

Hope this helps! 希望这可以帮助!

You can do it in one line so you will have your txt file in your .py file path: 您可以在一行中执行此操作,因此您将在.py文件路径中包含txt文件:

 my_file=open('{}.txt'.format(input('enter your name:')),'w')
 for i in range(1, 10):
    my_file.write(str(i))
 my_file.close()

Note: if you are using python 2.x use raw_input() instead of input . 注意:如果您使用的是python 2.x使用raw_input()而不是input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM