'How to copy a file without using shutil.copy
My teacher gave us a task: I gotta create 2 folders: folder1 folder2 And i gotta add a text file to folder1 then append asmthg on it (iknow i use f = open("//Folder1//text.txt", mode = a, encoding = "UTF-8) then f.append("Hello World!") and then i gotta copy the text file in folder1 to folder2 as text.txt(Copy) without using shutil.copyfile
So can anyone help about it?
Solution 1:[1]
If you have a .txt file you can always read it this way:
with open("file.txt", 'r') as file:
content = file.read()
and write to a file this way:
with open("otherfile.txt", 'w') as otherfile:
otherfile.write(content)
So this is the easier way to duplicate a file, since open with option 'w' (write mode) will automatically create the file if it doesn't exist.
In your case, since you have paths like r'\\Folder1\\text.txt' you just have to replace "file.txt" with your path, this way:
with open("\\Folder1\\text.txt", 'r') as file:
...
with open("\\Folder2\\text.txt", 'w') as newfile:
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FLAK-ZOSO |
