我想要的結果是,比較檔案中的每行,如果有不一樣就寫入到新的txt檔中,並將全部變成大寫
我自己是有寫了一點,可是都不能正常寫入到新txt中,我的代碼是如下
a= open("New.txt",'r')
b= open("Oldest.txt",'r')
c=open("Older.txt",'w')
while True:
linefilea = a.readline().strip()
linefileb =b.readline().strip()
if linefilea and linefileb:
if linefilea != linefileb:
c.write(linefilea.upper())
else:
print('沒有不同')
c.write(linefilea)
判斷結果都能正常運行
但是我的Older檔案都是空白的
請問我該怎麼寫呢?謝謝
a= open("New.txt",'r')
b= open("Oldest.txt",'r')
c=open("Older.txt",'w')
while True:
linefilea = a.readline().strip()
linefileb =b.readline().strip()
if linefilea and linefileb:
if linefilea != linefileb:
c.write(linefilea.upper())
else:
print('没有不同')
else:
break
a.close()
b.close()
c.close()
```python
a.close()
b.close()
c.close()
```
因为你使用了readline(),这样只会比较两个文件里的第一行数据。而根据你的描述,很有可能a或b的文件的第一行是空白,所以if linefilea and linefileb:这条语句判断为False.
如果需要比较所有内容,建议使用read(),如果需要逐段比较,可以使用readlines(),返回一个列表,再用列表遍历去逐行比较。