我有這個代碼:
import sys
cities = 'me, myself, eye'
company_types = 'WHAT, WHO'
with open("result.txt", 'w') as fid:
for city in cities:
for company_type in company_types:
fid.write(company_type.strip() " in " city.strip())
fid.write("\r\n")
我得到這個輸出:
<built-in method write of _io.TextIOWrapper object at 0x0000019E4C3017D0>
代碼有什么問題?我如何解決它?
uj5u.com熱心網友回復:
請將 city 和 company_types 轉換為串列或任何可迭代型別。
cities = ['me', 'myself', 'eye']
company_types = ['WHAT', 'WHO']
with open("/full/path/to/file/result.txt", 'w') as fid:
for city in cities:
for company_type in company_types:
fid.write(company_type.strip() " in " city.strip())
fid.write("\r\n")
嘗試使用完整路徑來確保在您想要的確切位置創建檔案,而不是 Python 當前路徑。
uj5u.com熱心網友回復:
import sys
#you are defining a string instead of a list, Try this.
cities = ['me', 'myself', 'eye']
company_types = ['WHAT', 'WHO']
with open("result.txt", 'w') as fid:
for city in cities:
for company_type in company_types:
fid.write(company_type.strip() " in " city.strip())
fid.write("\r\n")
uj5u.com熱心網友回復:
代碼沒問題,我剛剛檢查了一下。但是檢查你的檔案,可能它已經存在并且需要設定對它的訪問權限。或使用檔案的完整路徑。例如,如果我需要在我的腳本附近創建新檔案,我使用:
os.path.join(os.path.dirname(os.path.realpath(__file__)), "result.txt")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511136.html
標籤:Python循环嵌套的
