Answer the question
In order to leave comments, you need to log in
How to make a program read one file and write the changed data to another in Python?
There is a program that edits a file, how can I make it not edit the same file that I selected, but only read it and write the changes to another?
Here is the code
def change():
file_name = fd.askopenfilename()
f = open(file_name,'r')
lines = f.read()
lines = lines.replace('Путей в парке', '')
lines = lines.replace(';--------------', '')
while " " in lines:
lines = lines.replace(" ", " ")
level1 = None
level2 = None
for line in lines.split('\n'):
result1 = re.match('^@\s+(\d+)\s+(.*)$', line)
if result1:
level1 = f'{result1.group(1)};{result1.group(2)}'
continue
if re.match('#', line):
level2 = line
continue
if level1 and level2:
if level1 and level2 and line:
line = line.replace(' ', '; ')
print(f'{level1};{level2}{line}')
f.close()
save_changes = open(file_name, 'w')
save_changes.writelines(lines)
save_changes.close()
Answer the question
In order to leave comments, you need to log in
Something like this
with open('somefile', 'w+') as write_file:
with open('someotherfile', 'r') as read_file:
data = read_file.read()
outdata = f(data)
write_file.write(outdata)
# читаем исходник
text = open('file1.txt', 'r').read()
# изменяем
text += 'test'
# записываем во второй
f = open('file2.txt', 'w')
f.write(text)
f.close()
def change():
file_name = fd.askopenfilename()
file_name1 = 'второй файл'
f = open(file_name,'r')
lines = f.read()
lines = lines.replace('Путей в парке', '')
lines = lines.replace(';--------------', '')
while " " in lines:
lines = lines.replace(" ", " ")
level1 = None
level2 = None
for line in lines.split('\n'):
result1 = re.match('^@\s+(\d+)\s+(.*)$', line)
if result1:
level1 = f'{result1.group(1)};{result1.group(2)}'
continue
if re.match('#', line):
level2 = line
continue
if level1 and level2:
if level1 and level2 and line:
line = line.replace(' ', '; ')
print(f'{level1};{level2}{line}')
f.close()
save_changes = open(file_name1, 'w')
save_changes.writelines(lines)
save_changes.close()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question