2017-08-29 61 views
-1

我有这种情况:文件在Python复杂

  • 文件1命名的Source.txt
  • 文件2命名destination.txt

的Source.txt包含这些字符串:

MSISDN=213471001120 
MSISDN=213471001121 
MSISDN=213471001122 

我想看看destination.txt包含以下情况:

MSISDN = 213471001120 了Python代码首先执行

MSISDN = 213471001121 为蟒蛇的第二次执行代码

MSISDN = 213471001122 只有第三次执行o ˚FPython代码

我有这样的代码:

F1 = open("source.txt", "r") 
txt = F1.read(19) 
#print txt 

F2 = open("destination.txt", "w") 
F2.write(txt) 

F3=open("source.txt", "w") 
for ligne in F1: 
    if ligne==txt: 
     F3.write("") 
     break 

F1.close() 
F2.close() 
F3.close() 

的Source.txt文件是代码首次执行后空。

感谢高级。

+1

好歹,你不写什么'F3'。并且通过重新打开输出来破坏您的输入... –

+0

这可能更适合在Code Review交换站点上询问https://codereview.stackexchange.com/ – Erich

回答

1

您必须阅读整个文件,再次书写之前,因为模式w清空文件:

with open('source.txt') as lines: 
    lines = list(lines) 

with open('destination.txt', 'w') as first: 
    first.write(lines[0]) 

with open('source.txt', 'w') as other: 
    other.writelines(lines[1:]) 
0

你会需要一个外部文件来存储的“有多少次我运行状态之前”

with open('source.txt', 'r') as source, open('counter.txt', 'r') as counter, open('destination.txt', 'w') as destination: 
    num_to_read = int(counter.readline().strip()) 
    for _ in range(num_to_read): 
     line_to_write = source.readline() 
    destination.write(line_to_write) 

with open('counter.txt', 'w') as counter: 
    counter.write(num_to_read + 1) 

我已经改变了你的电话到open使用上下文管理器,所以你不需要在最后调用close

我还没有运行这个代码,所以可能会有一些错误。特别是,counter.txt不存在的情况下不处理。我会留给你的。

1

在决定下一步写什么之前,您需要比较destination.txt的当前内容。

此代码为我工作:

#!/usr/bin/env python 

file_src = open('source.txt', 'r') 
data_src = file_src.readlines() 

file_des = open('destination.txt', 'r+') # 'r+' opens file for RW 
data_des = file_des.read() 

if data_des == '': 
    new_value = data_src[0] 
elif data_des == data_src[0]: 
    new_value = data_src[1] 
elif data_des == data_src[1]: 
    new_value = data_src[2] 
else: 
    new_value = None 

if new_value: 
    file_des.seek(0) # rewind destination.txt 
    file_des.write(new_value)