Home > Software engineering >  read text file in python and give them different names according to line
read text file in python and give them different names according to line

Time:11-30

I have a folder with text files formatted like so:

Weather forecast
London
Monday, 1
Tuesday, 2
Wednesday, 3
Thursday, 4
Friday, 5

The first line of the file is the title; the second line is a sub-title; the rest of the file is a list of values, one per line.

I have been asked to write a function named read_file to return (title, subtitle, data_list), in this format:

'Weather forecast'
'London'
['Monday, 1\n', 'Tuesday, 2\n', 'Wednesday, 3\n', 'Thursday, 4\n', 'Friday, 5']

I have this code so far (including some code that I am instructed not to alter):

import sys

def read_file(file_name):

with open(file_name, 'w') as f:
    for line in f:
        line_list = line.split()
        lines = ""
        for lines in line_list:
            lines  = " "
            lines  = lines   "\n"
return

def main():
    # DO NOT EDIT THIS CODE
    input_file = ""
    args = sys.argv[1:]  
    if len(args) == 0:
        input_file = input("Please enter the name of the file: ")                    
    elif len(args) > 1:
        print('\n\nUsage\n\tTo visualise data using a sankey diagram type:\
            \n\n\tpython sankey.py infile\n\n\twhere infile is the name of \
            the file containing the data.\n')
        return         
    else:
        input_file = args[0]

# Section 1: Read the file contents
try:
    title, subtitle, data_list = read_file(input_file)
except FileNotFoundError:
    print(f"File {input_file} not found or is not readable.")
    return

if __name__ == "__main__":
    main()

How do I proceed from here?

CodePudding user response:

You can do something like this:

def read_file(file_name):
    with open(file_name) as file:
        title, subtitle, *lines = file.readlines()
        print(f"'{title[:-2]}'")
        print(f"'{subtitle[:-2]}'")
        print(lines)

CodePudding user response:

This would do it

lines = []
with open('scratch_10.txt') as f:
    title, subtitle, *rem = f.readlines()
    lines.append(title)
    lines.append(subtitle)
    lines.append(rem)

print(lines)
  • Related