program that takes a path to a file name as an argument (.txt file), reads the file and generates

Diposting pada

program that takes a path to a file name as an argument (.txt file), reads the file and generates a new file that has every alternate line swapped
In the new file, line 2 is line 1 of original file, line 3 of new file is line 4 of original file, line 4 of new file is line 3 of original file so on.
example textfile1 line1 line2 line3 line4 ”’
opening the file for reading
with open(“test.txt”, “r”) as textfile1:
content = file1.readlines()
creating a new file in write mode
with open(“testswap.txt”, “w+”) as file2:
for i in range(len(content)):

what logic should put here so in my new file could save “line2” as first line , “line1” as 2nd line , “line3” as 4th line, and “line4” as 3rd line.
file2.write(content[i].replace(“/n”,” “))

Answer
I think you are looking for something like this?
list1 = [“1 line”,
“2 line”,
“3 line”,
“4 line”,
“5 line”,
“6 line”,
“7 line”]

def swap_lines(list_object):
for index, value in enumerate(list_object):
if index % 2 == 0:
continue
else:
list_object[index], list_object[index -1] = list_object[index-1], list_object[index]
return list_object

for line in swap_lines(list1):
print(line)

Output:
2 line
1 line
4 line
3 line
6 line
5 line
7 line

 

 82 total views,  1 views today

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *