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

时间:2014-09-28 05:34:18

标签: python python-2.7

我想将输出保存为系统上的文本文件。输出文件的名称应该在命令提示符下从用户处获得。

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

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

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

这是正确的做法吗?

4 个答案:

答案 0 :(得分:2)

这样做

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))

答案 1 :(得分:1)

您可以执行以下操作:

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))

在此示例中,我们使用os.path.dirname(os.path.abspath(__file__))使用本地路径,我们将获取当前路径,我们将添加output.txt

  1. 详细了解abspath()外观here

  2. 详细了解外观here

  3. 在您的情况下,
  4. write方法会引发TypeError,因为i需要是string

答案 2 :(得分:0)

我做了几个改变。您需要执行以下操作:

    output + '.txt'

使用变量输出作为文件名。

除此之外,您需要通过调用str()函数将整数i转换为字符串:

    str(i)

因为write函数只接受字符串作为输入。

以下是所有代码:

    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()

希望这有帮助!

答案 3 :(得分:0)

您可以在一行中执行此操作,以便在.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()

注意:如果您使用python 2.x,请使用raw_input()代替input