如何在 Python 2.7 中打开、读取和写入文件——将代码从 fortran 90 转换为 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15728564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Open, Read, and Write files in Python 2.7 -- Converting code from fortran 90 to Python
提问by
I'm converting some code from fortran90 to python 2.7 and am having trouble understanding the arguments the in Open, Write, and Read functions in the fortran code, as well as knowing what elements are necessary to add to the code when I write it in python.
我正在将一些代码从 fortran90 转换为 python 2.7,并且无法理解 fortran 代码中的 Open、Write 和 Read 函数的参数,以及在我编写代码时知道需要将哪些元素添加到代码中Python。
Here are some blocks of the fortran code that I want to understand and convert to python:
以下是我想理解并转换为 python 的一些 Fortran 代码块:
OPEN(1,FILE=TRIM(filenameOut),RECL=2000)
WRITE(1,*) "tAge/yr (u-r) (u-z) fGas Mstars/MstarsOld"
CLOSE(1)
I'm guessing that the "1" is just assigning a label to the file name, the TRIM is removing any white space before or after the variable to which the python equivalent would be filenameOut.strip() or something. I'm unsure of what the RECL is doing and what the python equivalents for the other functions would be for this block.
我猜“1”只是为文件名分配一个标签,TRIM 正在删除变量之前或之后的任何空格,python 等效项是 filenameOut.strip() 或其他东西。我不确定 RECL 正在做什么以及该块的其他函数的 Python 等效项是什么。
Another example:
另一个例子:
OPEN(1,FILE=TRIM(filenameOut),RECL=2000)
WRITE(1,*) "(u-r) prob(u-r)"
DO countInside=1,nColourBins
WRITE(1,*) uMinusrMidpointsArray(countInside),probuMinusrArray(countInside)
CLOSE(1)
From this I would guess that the asterisk is meaning to write to the next line in the file. Again, I'm not sure how to do this in python yet.
由此我猜测星号的意思是写入文件的下一行。同样,我还不确定如何在 python 中做到这一点。
An example of reading in the fortran code:
读入fortran代码的一个例子:
OPEN(1,FILE=TRIM(filenameBC),RECL=2000)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
READ(1,*)
IOEnd=0
DO WHILE(IOEnd>-1)
READ(1,*,IOSTAT=IOEnd) logTime,Mbol,g,uMg,gMr,gMi,gMz
END DO
CLOSE(1)
I understand that the repeated READ(1,*) are simply reading off the first 7 lines of the file, but I'm unsure of any python equivalent shortcuts for this, i.e. a way to start at the 8th line or something.
我知道重复的 READ(1,*) 只是读取文件的前 7 行,但我不确定是否有任何 python 等效快捷方式,即从第 8 行或其他内容开始的方法。
采纳答案by agentp
as was noted last time you asked this, the recl= used with sequential access is not standard does nothing with at least one compiler, and almost certainly should be ignored.
正如您上次问这个问题时所指出的,用于顺序访问的 recl= 不是标准的,至少对一个编译器没有任何作用,几乎肯定应该被忽略。
In python you read lines as strings and process the string, something like this:
在 python 中,您将行读取为字符串并处理字符串,如下所示:
file=open(filename,'r')
for i in range(6):file.readline() #skipping 6 lines
items=file.readline().split()
items holds your values as strings.. you then convert each based on type:
items 将您的值保存为字符串..然后您根据类型转换每个值:
logTime=float(item[0])
i just winged this without testing..but it should get you started.
我只是在没有测试的情况下完成了这个……但它应该让你开始。
One gotcha, fortran with the "*" will read from multiple lines if needed. I doubt this is the case here but for completeness you need to do something like this,
一个问题,如果需要,带有“*”的 fortran 将从多行读取。我怀疑这里的情况是这样,但为了完整起见,你需要做这样的事情,
items=[]
while len(items)<nrequired:items.extend(file.readline().split())
for writing you can try:
对于写作,您可以尝试:
file=open(filename,'r')
file.write(' '.join([repr(x) for x in (v1,v2,v3)])+'\n')
or
或者
file.write(('%.14g'+(' %.14g'*2)+'\n')%(v1,v2,v3))
(need to count how many values you have to put the "*2" )
neither of these gives you the exact output you'd get from fortran. If you need the same spacing, decimal places, etc see Vladimirs comment.. (If a value in python is 0.1 there is not a simple way to force printing the trailing zeros 0.100000 as you would get with fortran )
这些都不能为您提供从 fortran 获得的确切输出。如果您需要相同的间距、小数位等,请参阅 Vladimirs 评论..(如果 python 中的值为 0.1,则没有一种简单的方法可以像使用 fortran 那样强制打印尾随零 0.100000 )
回答by Vladimir F
Your first example is clearly wrongly parenthesized. It should be like in the second one.
你的第一个例子显然是错误的括号。应该和第二个一样。
Trim only clears the trailing spaces. Here it is probably not needed.
Trim 只清除尾随空格。这里可能不需要它。
In your case the file will be connected to the sequential access. In this case RECL sets the maximum record length for the file (this means line length). It is quite possible you can ignore it.
在您的情况下,文件将连接到顺序访问。在这种情况下,RECL 设置文件的最大记录长度(这意味着行长度)。您很可能可以忽略它。
The asterisk in the second position of the I/O statements means the usage of the list-directed format. This gives the compiler some freedom in how exactly format the output. In particular, he compiler continues on the next line (record), if the output is too long, or if the input does not contain all te items in the current one.
I/O 语句第二位的星号表示使用列表导向格式。这使编译器在如何准确格式化输出方面具有一定的自由度。特别是,如果输出太长,或者如果输入不包含当前行中的所有 te 项,则编译器会继续下一行(记录)。
So, READ(1,*,IOSTAT=IOEnd) logTime,Mbol,g,uMg,gMr,gMi,gMzcan read from 1 line, if it contains 7 items, but it can also red from 7 lines with one item. You must count with this in your Python code, if you want to keep this flexibility.
所以,READ(1,*,IOSTAT=IOEnd) logTime,Mbol,g,uMg,gMr,gMi,gMz可以从 1 行读取,如果它包含 7 个项目,但它也可以从 7 行读取一个项目。如果您想保持这种灵活性,您必须在 Python 代码中考虑到这一点。
WRITE(1,*) uMinusrMidpointsArray(countInside),probuMinusrArray(countInside)should write only to one line, as it is only two items, unless they are long strings.
WRITE(1,*) uMinusrMidpointsArray(countInside),probuMinusrArray(countInside)应该只写入一行,因为它只有两个项目,除非它们是长字符串。
回答by Adward
from sys import argv
从系统 import argv
script,
脚本,
filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()

