当前节目:
#!/usr/bin/python
lookup = 'Loop time'
with open('log.lammps') as myFile:
found = []
for num, line in enumerate(myFile, 1):
if lookup in line:
print 'found at line:', num
found.append(num)
print found
a = int(found[0])
b = int(found[1])
c = int(found[2])
d = int(found[3])
lookup = 'Memory usage per processor ='
with open('log.lammps') as myFile:
found2 = []
for num, line in enumerate(myFile, 1):
if lookup in line:
print 'found at line:', num
found2.append(num)
print found2
e = int(found2[0])
f = int(found2[1])
g = int(found2[2])
h = int(found2[3])
x = 0
while x < len(found):
a = found[x]
e = found2[x]
print "Some thing useful!"
for w,line in enumerate(open("log.lammps")):
if w >= e and w < a :
print line,
x += 1
如何将最后一个while函数存储到文档中。我希望它用这个程序打印出的数据创建一个文件,这样我就可以让matlab读取该文件了。
答案 0 :(得分:0)
最简单的解决方案是将输出重定向到文件。让script.py
成为你的python脚本:
./script.py > out.txt
否则,您可以直接在python中将stdout
重定向到文件。
#!/usr/bin/python
import sys
sys.stdout = open('out.txt', 'w')
lookup = 'Loop time'
...
现在每个print
语句都会重定向到out.txt
答案 1 :(得分:0)
一种非常快捷的方法是用开放文件描述符替换sys.stdout
。
f = open("file.txt","w")
old_stdout = sys.stdout
sys.stdout = f
while x < len(found):
a = found[x]
e = found2[x]
print "Some thing useful!"
for w,line in enumerate(open("log.lammps")):
if w >= e and w < a :
print line,
x += 1
sys.stdout = old_stdout
f.close()
这会自动将您打印的所有内容重定向到file.txt
而不是stdout
。不过,它也有点像个hackish。最好只打开写文件,然后用print ...
替换f.write(...)
,因为你没有任何复杂打印功能。
(我假设您只想将最后一个while
循环写入文件,正如您的问题所述。)
答案 2 :(得分:0)
在开始时打开文件并随时写入数据:
with open('output.txt',"w") as out:
无论您在何处打印数据,只需将其写入文件:
print 'found at line: {}'.format(num)
out.write('found at line: {}\n'.format(num)) etc..
只需启动您的代码:
with open('output.txt',"w") as out:
with open('log.lammps') as myFile:
# continue with your code
答案 3 :(得分:-1)
关于sys.stdout
的重要一点是,您必须import sys
而不是from sys import stdout
即。 赢了将输出重定向到文件:
>>> from sys import stdout
>>> stdout = open('/dev/null', 'w')
>>> print 1
1 # not working