用Python读/写文件 [英] Reading/writing files in Python
问题描述
我正在尝试从罗素2k中创建一个新的包含股票代号的文本文件,如下所示:
I am trying to create a new text file of stock symbols in the russell 2k from one that looks like this:
我想要的是每行末尾的股票代码.所以我有以下代码:
All I want is the ticker symbol at the end of each line. So I have the following code:
with open("russ.txt", "r") as f:
for line in f:
line = line.split()
line = line[-1]
if line == "Ticker": continue
print line
with open("output.txt", "w") as fh:
fh.seek(0,2)
print line
fh.write(line)
我在output.txt
文件中最后得到的只是一行,并且列表中的最后一个股票代号而不是所有股票代号.我认为每次使用fh.seek(0,2)
都会在末尾创建新行.我究竟做错了什么?另外,实际上,我不需要创建另一个文档,我可以只编辑当前文档,但是我也无法弄清楚,因此如果您可以向我展示如何只写一个同样可以接受的文件,那么我也可以.
All I end up with in the output.txt
file is one line with the very last ticker in the list instead of all the tickers. I thought using fh.seek(0,2)
would create a new line at the end each time through. What am I doing wrong? Also, in reality I don't need to create another doc, I could just edit the current one but I couldn't figure that out either so if you could show me how to just write to the same file that also is perfectly acceptable.
推荐答案
文件模式"w"
在每个步骤中都会创建一个新的空文件.可以使用模式"a"
进行追加,也可以将文件打开的位置移到循环外部.
The filemode "w"
creates a new empty file in each step. Either use mode "a"
for append, or move the file opening outside the loop.
with open("russ.txt", "r") as f:
for line in f:
line = line.split()
line = line[-1]
if line == "Ticker": continue
print line
with open("output.txt", "a") as fh:
fh.write(line + "\n")
或者更好,只打开一次文件:
or better, open the file only once:
with open("russ.txt", "r") as f, open("output.txt", "w") as fh:
for line in f:
symbol = line.split()[-1]
if symbol != "Ticker":
print symbol
fh.write(symbol + "\n")
这篇关于用Python读/写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!