У меня есть следующий код, в котором комментарии объясняют вывод и желаемый результат. Кажется, я не могу получить доступ (или понять логику), как обращаться к различным полям в списке.Доступ к первому столбцу в каждой строке в списке Python
def viewrecs(username):
username = (username + ".txt")
with open(username,"r") as f:
fReader=csv.reader(f)
for row in fReader:
for field in row:
#print(field) #this prints everything in the file
#print(row) #this also prints everything in the file
#print(row[0]) #this also prints everything!!!!!!
#print(field[0]) #this prints the first ELEMENT in each row, namely the "["
#How do I access the first field of each column (the genre, like SCI-FI, or Romance)
Этот файл представляет собой текстовый файл, основанный на имени пользователя. Содержание является:
"['Sci-Fi', 'Blade Runner']"
"['Sci-Fi', 'Star Trek']"
"['Sci-Fi', 'Solaris']"
"['Sci-Fi', 'Cosmos']"
"['Drama', ' The English Patient']"
"['Sci-Fi', 'Out of the Silent Planet']"
"['Drama', ' The Pursuit of Happiness']"
"['Drama', ' The English Patient']"
"['Drama', ' Benhur']"
"['Drama', ' Benhur']"
Ответ о том, как получить доступ к полю столбца (например, Sci-Fi, драма и т.д.), и объяснение было бы оценено.
Я хочу распечатать весь первый столбец .... т.е. SCI-FI, SCI-FI, SCI-FI, DRAMA и т. Д. Мне нужно, чтобы они были прочитаны в списке идеально, чтобы они могли быть управляемый внутри списка
На основании одного из приведенных ниже ответов, ЕСЛИ проблема связана с тем, как данные были записаны в файл в первую очередь, код/функция, которая записывает эти данные в файл, находится ниже :
def viewfilmfunction(x,username):
#open the file as student file (variable)
print(username, ":You are about to view Film:", x, "Enter the selection ID number of the film again to confirm viewing")
with open("films.txt","r") as filmsfile:
#prompt the user to enter the ID number they require
idnumber=input("Enter the ID number you require:")
#call upon our reader (this allows us to work with our file)
filmsfileReader=csv.reader(filmsfile)
#for each row that is read by the Reader
for row in filmsfileReader:
#and for each field in that row (this does it automatically for us)
for field in row:
#if the field is equal to the id number that is being searched for
if field ==idnumber:
#print the row fields (genre and title) corresponding to that ID number
#create a list which contains the relevant fields in the row.
viewedlist=[row[1],row[2]]
print("You have viewed:", viewedlist)
with open("fakeflixfile.txt","r")as membersfile:
#Open Reader
membersfileReader=csv.reader(membersfile)
for row in membersfileReader:
for field in row:
if field==username:
#Open Writer to append to file -this time it looks for the file stored by that username
with open("%s.txt" % username,"a") as membersfile:
membersfileWriter=csv.writer(membersfile)
#Use the writer to append the viewedlist to the appropriate member's user file.
membersfileWriter.writerow([viewedlist])
содержание FAKEFLIXFILE.txt
username13022,[email protected],user,name1,2/02/3022,user Road,US455P,Mle,Nothing,[email protected] AugustineSalins1900.txt,[email protected],Augustine,Salins,5/02/1900,Hutchins Road,CRBBAAA,Male,Theology,[email protected] JosieBletchway3333,[email protected],Josie,Bletchway,29/02/3333,Bletch Park,BB44AA,Female,Encryption,[email protected] JoeBloggs.0.0,[email protected],Joe,Bloggs,0.0.0.0,0 Road,00000,Male,Joe Blogs,[email protected]
UPDATE: Я теперь изменил текстовый файл (на основе имени пользователя), так что сформированное не создает список:
Drama, The English Patient
Drama, Benhur
Sci-Fi,Cosmos
Однако на бег:
def viewrecs(username):
#pass
username = (username + ".txt")
with open(username,"r") as f:
fReader=csv.reader(f)
for row in fReader:
print(eval(row)[0])
Ошибка сохранилась:
print(eval(row)[0])
TypeError: eval() arg 1 must be a string, bytes or code object
Как ваш «fakeflxfile.txt» выглядит как? Можете ли вы вставить несколько строк? – Vlad
вставлял содержимое FAKEFLIXFILE.txt в приведенном выше редакторе –
, потому что вы хотите получить доступ к файлу csv и получить доступ к определенным столбцам, которые вы могли бы попробовать использовать 'dataframe' с' pandas', если реализация pandas является опцией. Это было бы довольно прямолинейно в создании всего содержимого и легко доступ к строкам и столбцам. – arde