Reputation: 11
Folks,
I have a difficulty here to manipulate files.
Objective: I'm developing a script that needs to create folders and copy files from a source, the script reads the user the number of months to create. The script replicates the files equal the number of months to be created, if in 2017 need to change a string to a .txt file into the directory.
original string within the file: ANO INICIO DO ESTUDO 2016 String is to be changed: ANO INICIO DO ESTUDO 2017
PS: The file to be changed is not the original but a copy
It is possible to change a line from a txt file?
What I need:
Read program source file and play to an array identifying a portion of a string within the array modify the string if it is found to be part of the string delete the source file and write another with the same name, or simply change a string (a word in a row) within the source file.
FILENAME_NEWAVE = Path of the source file
STRING_DGER = String to be searched
FILE_DATE = Year
This is not working, you are writing in the source file
def find_word_in_file_dger(FILENAME_NEWAVE, STRING_DGER, FILE_DATE):
f = open(FILENAME_NEWAVE, "r+")
file_array = f.readlines()
for i in file_array:
if i.find(STRING_DGER.encode('utf-8')):
f.write(i)
else:
print ("TO LENDO O ARRAY")
if FILE_DATE == "2016":
continue
else:
i.replace(STRING_DGER, "ANO INICIO DO ESTUDO " + FILE_DATE)
f.write(i)
print("TO ESCREVENDO A LINHA CORRETAMENTE MLK!! ")
return i
f.close()
return False
Upvotes: 0
Views: 65
Reputation: 2303
I'm pretty sure this will work. Regarding the UnicodeDecodeError ill suggest you give a look at this
import re
cache = None
with open("file.txt", "r") as f:
cache = f.read()
new_file = re.sub("2017", "2018", cache)
new_file = re.sub("2016", "2017", new_file)
if new_file:
with open("newfile.txt", "w") as f:
f.write(new_file)
Upvotes: 0