我正在阅读地图文件并将列格式的数据写入文本文件。我写的代码如下,但它不适合我。
@Override
public void beforeCompletion() {
LOG.trace( "Transaction before completion callback" );
if ( !transactionCoordinator.isActive() ) {
return;
}
boolean flush;
try {
final int status = transactionCoordinator.getTransactionContext().getTransactionEnvironment()
.getJtaPlatform().getCurrentStatus();
flush = managedFlushChecker.shouldDoManagedFlush( transactionCoordinator, status );
}
catch ( SystemException se ) {
setRollbackOnly();
throw exceptionMapper.mapStatusCheckFailure(
"could not determine transaction status in beforeCompletion()", se );
}
try {
if ( flush ) {
LOG.trace( "Automatically flushing session" );
transactionCoordinator.getTransactionContext().managedFlush();
}
}
catch ( RuntimeException re ) {
setRollbackOnly();
throw exceptionMapper.mapManagedFlushFailure( "error during managed flush", re );
}
finally {
transactionCoordinator.sendBeforeTransactionCompletionNotifications( null );
transactionCoordinator.getTransactionContext().beforeTransactionCompletion( null );
}
}
预期的输出是
fo = open(filename, "r+")
fu = open("map.txt","w+")
for line in fo:
if (".data.g" in line):
fu.write(line)
print line,
fo.close()
fu.close()
#to remove unwanted data
f = open("map1.txt", "w+")
g = open("map.txt", "r+")
for line in g:
if((".data " in line) and (".bss" in line) and(".text" in line )):
break
else:
f.write(line)
f.write('\n')
f.close()
g.close()
输入地图文件的格式为
2007c04c .data g_isr_array
2007c004 .data g_retry_count
2007c000 .data g_pkt_hist_wptr
我想只读取以“.data.g”开头的全局变量,但地址位于我的代码无法读取的下一行。
答案 0 :(得分:1)
以下是一些步骤:
line[0:7]
并与'.data.g'
进行比较,看看它是否是您想要的行。如果是,请使用line.split()拆分该行,并在.data之后提取该部分。通过切割字符串。要获得下一行的地址,您需要向前移动一行。请参阅此链接以了解如何操作:Python: For loop with files, how to grab the next line within forloop?
获得该行后,执行字符串拆分并切片以获取地址。现在使用所有三个数据项,写入文件。
对于line[0:7] == '.data.g'
条件的任何行,请跳过
示例:
with open('map.txt', 'r') as readF:
with open('map1.txt', 'w') as writeF:
for line in readF:
if line.startswith('.data.g'):
try: # next() can cause StopError, gotta catch it
row = line.split()
part_after_data = row[0][6:]
line = next(ireadF)
addr = line.split()[0]
writeF.writeline(addr + ' .data '+ part_after_data )
except:
pass
答案 1 :(得分:1)
如果数据的格式和顺序已发布,那么您真的只想要第一行不以-es6.js
开头:
.data
使用您的输入将为您提供:
from itertools import imap
with open("map.txt") as f:
rows = imap(str.split, f)
for row in rows:
if row[0] != ".data":
a, b = row[0].rsplit(".", 1)
print(next(rows)[0],a, b)
您还可以使用以('0x2007c000', '.data', 'g_pkt_hist_wptr')
('0x2007c004', '.data', 'g_retry_count')
('0x2007c005', '.data', 'g_our_node_id')
开头的行:
.data.
这会给你相同的结果。