Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python复合体中的文件_Python_File - Fatal编程技术网

Python复合体中的文件

Python复合体中的文件,python,file,Python,File,我有这样的情况: 名为source.txt的文件1 名为destination.txt的文件2 source.txt包含以下字符串: MSISDN=213471001120 MSISDN=213471001121 MSISDN=213471001122 我想看到destination.txt包含以下案例: MSISDN=213471001120仅用于第一次执行python代码 MSISDN=213471001121仅用于第二次执行python代码 MSISDN=213471001122仅用

我有这样的情况:

  • 名为source.txt的文件1
  • 名为destination.txt的文件2
source.txt包含以下字符串:

MSISDN=213471001120
MSISDN=213471001121
MSISDN=213471001122
我想看到destination.txt包含以下案例:

MSISDN=213471001120仅用于第一次执行python代码

MSISDN=213471001121仅用于第二次执行python代码

MSISDN=213471001122仅用于第三次执行python代码

我有以下代码:

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文件为空


Thank在advanced中。

在再次写入之前,您必须阅读整个文件,因为模式
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:])

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

我已将您的调用更改为
open
以使用上下文管理器,这样您就不需要在最后调用
close


我还没有运行这段代码,所以可能有一些bug。特别是,不处理
counter.txt
不存在的情况。我将由您决定。

在决定下一步编写什么之前,您需要比较
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)

无论结果如何,您都不会向
F3
写入任何内容。您通过将输入作为输出重新打开来销毁它……这可能更适合在代码复查交换站点上询问
#!/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)