-2

I want to read a simple list from a file. But can't separate list elements from one another.

Here's my file:

"11","Arial","red","white","black","200x200","My Project"

Here's my read function:

def fread(file_name):
    user_file=open('{}'.format(file_name),"r")
    file_content=user_file.read()
    user_file.close()
    return str(file_content)

Here's the part that does not work:

conf_file=fread("settings")
conf_file.split(",")
print(conf_file[2])

This returns 1 instead of red

299792458
  • 3
  • 2

3 Answers3

0

You can use csv module.

import csv

def fread(file_name):
    with open(file_name) as f:
        return next(csv.reader(f))

print(fread("file.name"))
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
-1

str.split does not mutate strings as they are immutable. You need to assign the return value back to the variable:

conf_file = fread("settings")
conf_file = conf_file.split(",")
print(conf_file[2])

The line containing:

open('{}'.format(file_name), 'r')

Can just be written as the following if you do not need to amend the input string:

open(file_name, 'r')

Since all of your items are enclosed within double quotes, Python will include them in the string. If you want to only use the values inside the strings, you need to use a slice of the string to remove them. Add this line after you split by commas:

conf_file = [value[1:-1] for value in conf_file]

Now data like '"11"' will just be '11'. Note that this does not convert the string 11 into the int 11.

N Chauhan
  • 3,407
  • 2
  • 7
  • 21
-1

You need to split on the "commas", and remove the enclosing double-quotes -

Also, no need for a four line function to read the file contents:

conf_file = [part.strip('"') for part in open(filename).read().split(",")]
jsbueno
  • 99,910
  • 10
  • 151
  • 209