[英]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.