+ 2

to open a file in python and print the first word and the last word of the first line, and so on with all the lines of the file.

Hello everyone !! I have a problem: I want to open a file in python and print the first word and the last word of the first line, and so on with all the lines of the file. Can anybody help me ?

29th Jan 2018, 1:20 AM
Srt
Srt - avatar
2 ответов
+ 5
f = open("filename.ext", "r") # open the file in readonly mode lines = [] # create an empty list to store the lines in the file for line in f: lines.append(line) # loop over the lines in the file and store them in the lines list for line in lines: words_in_line = line.split() # create a list of the words in each line print(word_in_line[0], words_in_line[-1]) # print out the 1st and last word of each line OR do it all in 1 loop f = open("filename.ext", "r") for line in f: words = line.split() print(words[0], words[-1])
29th Jan 2018, 2:09 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
if I wanted to do that, I would use the shutil module for the file handling https://docs.python.org/3.0/library/shutil.html after using that to open the file I would write a for loop to iterate over each line and print the first and last word
29th Jan 2018, 1:48 AM
LordHill
LordHill - avatar