简体   繁体   English

如何创建一个新文件并将现有文件的内容复制到新创建的文件python中

[英]How to create a new file and copy content of existing file into newly created file python

I have a python function here that takes in 2 params, old_file is the name of the file that contains the content that I want to copy over to the new file and the new_file is the name for the file I want to create.我这里有一个 python 函数,它接受 2 个参数,old_file 是包含我想要复制到新文件的内容的文件的名称,new_file 是我想要创建的文件的名称。 Right now my code looks like this and it would throw an error which is a type error that says "TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper".现在我的代码看起来像这样,它会抛出一个错误,它是一个类型错误,上面写着“TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper”。 Is there a more efficient way to do it?.有没有更有效的方法来做到这一点? In addition when I point at with open(file, "r+") as f2: I get this warning另外,当我用 open(file, "r+") 作为 f2 指向时:我收到此警告

Note.笔记。 this works if the file is already pre-made but not when i make it in the function如果文件已经预先制作,这有效,但当我在函数中制作时无效

def copy_In(old_file, new_file):

    file = open(new_file, "w")

    with open(file, "r+") as f2:
        for x in range(10):
            f2.readline()
        pos = f2.tell()
        f2_remainder = f2.read()
        f2.seek(pos)
        with open(old_file, "r") as f1:
            for line in f1:
                f2.write(line)
        f2.write(f2_remainder)

错误

just do it like:只是这样做:

def copy_file(old_fname, new_fname):
    with open(old_fname, "rt") as old_fobj, open(new_fname, "wt") as new_fobj:
        new_fobj.write(old_fobj.read())

we are opening first file in read mode and second in write mode and reading the entire content of first file and writing it in second file.我们以读取模式打开第一个文件,以写入模式打开第二个文件,然后读取第一个文件的全部内容并将其写入第二个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 修改代码以在新创建的文件夹中创建文件 - Modify code to create file in newly created folder Python:将文件移动到新创建的目录 - Python: moving file to a newly created directory 使用python创建.bat文件运行新创建的.bat文件不起作用 - Using python to create .bat file and the run the newly created .bat file does not work 在 Python 中更改新创建的 HTML 文件的权限时没有此类文件错误 - No such file error when changing permissions of newly created HTML file in Python Python-将内容写入现有文件 - Python - Write content into existing file 如何创建用python创建的数据的csv文件 - How to create a csv file of data created in python 如何在子进程python中创建和复制文件的内容 - How to create, and copy the contents of a file in subprocess python 如何基于.csv 文件创建多个.md 文件并将.csv 文件的正确行输入到每个新创建的.md 文件中? - How to create multiple .md files based on a .csv file and enter the correct rows of the .csv file into each newly created .md file? 如何在不覆盖现有文件的情况下在 python 中创建文件 - How do I create a file in python without overwriting an existing file python:sys.argv输入未显示在新创建的文件中 - python: sys.argv input not showing in newly created file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM