程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python 写入文件后读取为空的问题

发布于2019-08-17 20:44     阅读(672)     评论(0)     点赞(0)     收藏(1)


python 写入文件后读取为空的问题

写一个小程序的时候,用到了py的文件处理方法。但是当我在写入后,立马使用readlines方法读取,读取为空。

import os
store_file = 'E:'
old_content_path = store_file + "old.txt"
new_content_path = store_file + "new.txt"
copy_content_path = store_file + "copy.txt"
old_content_file = open(old_content_path, 'w+')  #储存需要备份的文件内容
new_content_file = open(new_content_path, 'w+')  #储存已备份文件夹中的内容
copy_content_file = open(copy_content_path, 'w+')        #储存需要复制的内容
old_path = 'E:\\Honor数据备份\\Pictures\\iphone'
new_path = 'E:\\Honor数据备份\\Pictures'
def readFileList(path,filename):
    for (root,dirs,files) in os.walk(path):
        for every_root in root:    
            for every_files in files:
                filename.write(str(root)+'\\'+str(every_files)+'\n')      
    print('完成文件写入')
readFileList(old_path,old_content_file)
readFileList(new_path,new_content_file)
old_content = old_content_file.readlines()
new_content = new_content_file.readlines()
old_content_file.close()
new_content_file.close()
print(new_content)
print(old_content)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

完成文件写入
完成文件写入
[]
[]
PS D:\Project\SyncPhoto>

结果读取出来的数组全为空。
思考一番,我猜想,怕不是需要重新打开一次文件?然后就试了一下。

import os

copy_file =[[],[],[]]
store_file = 'E:'
old_content_path = store_file + "old.txt"
new_content_path = store_file + "new.txt"
copy_content_path = store_file + "copy.txt"
old_content_file = open(old_content_path, 'w')  #储存需要备份的文件内容
new_content_file = open(new_content_path, 'w')  #储存已备份文件夹中的内容
copy_content_file = open(copy_content_path, 'w')        #储存需要复制的内容

old_path = 'E:\\Honor数据备份\\Pictures\\iphone'
new_path = 'E:\\Honor数据备份\\Pictures'


def readFileList(path,filename):
    for (root,dirs,files) in os.walk(path):
        for every_root in root:    
            for every_files in files:
                filename.write(str(root)+'\\'+str(every_files)+'\n')      
    print('完成文件写入')
readFileList(old_path,old_content_file)
readFileList(new_path,new_content_file)


old_content_file.close()
new_content_file.close()

old_content_file = open(old_content_path, 'r')  #储存需要备份的文件内容
new_content_file = open(new_content_path, 'r')  #储存已备份文件夹中的内容

old_content = old_content_file.readlines()
new_content = new_content_file.readlines()

print(new_content)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

就填上了python 写入文件后需要重新打开一次文件进行读取这个坑。



所属网站分类: 技术文章 > 博客

作者:黎明要到来了

链接:https://www.pythonheidong.com/blog/article/48429/922474c87cacdcbe5988/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)