美文网首页
创建文档时报错:No such file or director

创建文档时报错:No such file or director

作者: lalalasa | 来源:发表于2020-06-14 17:35 被阅读0次

    在使用seek创建指定大小的文档是,采用的是生成新文档,再在指定位置写入文字来设置文档大小,但是实践过程中发现,总是卡在创建文档上,提示文档不存在

    def gen_file(size):
            path = "/Users/xxx/"
            file_name = "gen_{}MB.csv".format(size)
            file_path = path + file_name
    
            fo = open(file_path, "rw+")  # create if not exist
            fo.seek(1024*1024*size)  # MB
            fo.write("\x00")
            fo.close()
            
            print("success")
    
    gen_file(10)
    
    (v2) ➜  ~ python /Users/xxx/generate_sized_file.py
    Traceback (most recent call last):
      File "/Users/xxx/generate_sized_file.py", line 20, in <module>
        gen_file(10)
      File "/Users/xxx/generate_sized_file.py", line 9, in gen_file
        fo = open(file_path, "rw+")
    IOError: [Errno 2] No such file or directory: '/Users/xxx/gen_10MB.txt'
    (v2) ➜  ~ 
    (v2) ➜  ~ python /Users/xxx/generate_sized_file.py
    success
    

    修改脚本中的fo = open(file_path, "rw+")fo = open(file_path, "w+"),就成功了,原因是……r是只读,得有写权限,所以要有'w'

    mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.
    

    'r':只读
    'w':只写
    'r+':读写
    当不知道mode时,默认为'r'

    参考:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

    相关文章

      网友评论

          本文标题:创建文档时报错:No such file or director

          本文链接:https://www.haomeiwen.com/subject/xnxfxktx.html