簡體   English   中英

如何將輸出保存為.txt文件?

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

我想將輸出保存為我的系統上的文本文件。 輸出文件的名稱應該在命令提示符下從用戶處獲得。

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

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

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

這是正確的做法嗎?

這樣做

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

您可以執行以下操作:

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()更多信息, abspath()查看此處

  2. 閱讀更多關於這里的內容

  3. 在你的情況下write方法將引發TypeError,因為i需要是一個string

所以我做了幾個改變。 你需要做一些事情:

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

希望這可以幫助!

您可以在一行中執行此操作,因此您將在.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM