[英]Redirect print output to file in Python
我試圖將打印輸出重定向到Python 3.4中的文件-現在,因為它將我的腳本打印輸出到了shell中。 我真的不需要這樣做。 這是我的代碼:
with open('Input.txt') as namelist:
for line in namelist:
line_lower = line.lower()
a = namelist.readline()
if fuzz.ratio(a, line) >= 95:
print(fuzz.ratio(a, line))
print(a + ": " + line)
我真的很想知道由此產生的結果:
print(fuzz.ratio(a, line))
print(a + ": " + line)
輸出到文本文件。
到目前為止,我發現的內容似乎不適用於Python 3,因為print語句現在是需要括號而不是語句的函數。 這是不起作用的示例:
f = open('out.txt', 'w')
print >> f, 'Filename:', filename # or f.write('...\n')
f.close()
Python 3.0引入了支持可選參數file
的print()
函數。 所以你可以做類似的事情
with open("myfile.txt", "w") as f:
print("Hello, world!", file=f)
更多信息在這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.