老师给我们布置了一个任务: 我要创建 2 个文件夹:folder1、folder2 我必须将一个文本文件添加到folder1 然后在其上附加 asmthg (我知道我使用 f = open("//Folder1//text.txt", mode = a,encoding = "UTF-8) 然后 f.append("Hello World!") 然后我必须将folder1中的文本文件作为text.txt(复制)复制到folder2,而不使用shutil.copyfile
那么有人可以帮忙吗?
如果您有
.txt
文件,您可以随时以这种方式阅读:
with open("file.txt", 'r') as file:
content = file.read()
并以这种方式写入文件:
with open("otherfile.txt", 'w') as otherfile:
otherfile.write(content)
因此,这是复制文件的更简单方法,因为带有选项 open
(写入模式)的
'w'
(写入模式)将自动创建文件(如果文件不存在)。
在你的情况下,因为你有像
r'\\Folder1\\text.txt'
这样的路径,你只需要用你的路径替换“file.txt”,这样:
with open("\\Folder1\\text.txt", 'r') as file:
...
with open("\\Folder2\\text.txt", 'w') as newfile:
...
@FLAK-ZOSO的回答就够了;我想分享一个更完整的代码
def readfile(file="uid.txt", mod="r", cont=None, jso: bool = False):
if not mod in ("w", "a", "wb", ):
assert os.path.isfile(file), str(file)
assert cont is None
if mod == "r":
with open(file, encoding="utf-8") as file:
lines: list = file.readlines()
return lines
elif mod == "_r":
with open(file, encoding="utf-8") as file:
contents = file.read() if not jso else json.load(file)
return contents
elif mod == "rb":
with open(file, mod) as file:
contents = file.read()
return contents
else:
fil_e = open(file, mod, encoding="utf-8") if not mod == "wb" else open(file, mod)
if not jso:
fil_e.write(cont)
else:
assert not mod == "wb"
json.dump(cont, fil_e, indent=2, ensure_ascii=False)
fil_e.close()
cont = readfile(file='file.bla', mod="rb")
readfile(file='otherfile.bla', mod="wb", cont=cont)