I was trying to get value from .txt file into array/list in python.
Let's say I have this data in user.txt :
ghost:001
ghost:002
ghost:003
So, when I want to output it as :
'ghost:001','ghost:002','ghost:003'
I use this function
def readFromFile(filename, use_csv):
userlist = ''
userlist_b = ''
print ("Fetching users from '%s'"% filename)
f = open (filename,"r")
for line in f:
userlist+=str(line)
userlist = "','".join(userlist.split("\n"))
userlist = "'" + userlist + "'"
userlist = "(%s)" %userlist
return userlist
My question is how could I do this:
I want to print specific user. Something like
idx = 2
print("User[%s] : %s",%idx, %(array[idx]))
*output:*
User[2] : ghost:003
How do I form the array?
Could anyone help me?
I would store the users in a dict where the keys increment for each user:
d = {}
with open("in.txt") as f:
user = 1
for line in f:
d[user]= line.rstrip()
user += 1
print(d)
{1: 'ghost:001', 2: 'ghost:002', 3: 'ghost:003'}
If you just want a list of user and to access by index:
with open("in.txt") as f:
users = f.readlines()
print("User {}".format(users[0]))
User ghost:001
Look into loading dictionaries. This code should help you.
import json
import pickle
d = { 'field1': 'value1', 'field2': 2, }
json.dump(d,open("testjson.txt","w"))
print json.load(open("testjson.txt","r"))
pickle.dump(d,open("testpickle.txt","w"))
print pickle.load(open("testpickle.txt","r"))
If you want the file (one big string) split out into smaller strings, don't build up a new string, then split it apart again. Just append each line to a list:
def readFromFile(filename, use_csv):
userlist = []
print ("Fetching users from '%s'"% filename)
with open(filename,"r") as f:
for line in f.read():
userlist.append(line)
return userlist
array = readFromFile('somefile', use_csv)
idx = 2
print("User[%s] : %s" % (idx, array[idx]))
Not sure about the User['idx'] part of you desire.
Try to use list comprehensions.
Use indexing rather than dictionaries if that's all you need. (I can add a dict version if the seconds part of the line is really the index you are looking up)
# read the file and use strip to remove trailing \n
User = [line.strip() for line in open(filename).readlines()]
# your output
print "User[2] : %s"%User[2]
# commented line is more clear
#print ','.join(User)
# but this use of repr adds the single quotes you showed
print ','.join(repr(user) for user in User)
output:
User[2] : ghost:003
'ghost:001','ghost:002','ghost:003'
Related
I'm tasked to create a function that takes a string filename as an argument, reads the file with the name filename, and prints
all confirmed reservations in order of the time.
A line in the file is formatted like so
name, time, reservation_status (can either be confirmed or canceled in uppercase)
An example of a file "reservations.txt" could look like this:
Alex, 20, CONFIRMED
Thomas, 16, CANCELLED
William, 18, CONFIRMED
The correct output when calling the function on this example file should look like this:
show_reservations("reservations.txt")
>>> William, 18
Alex, 20
My solution:
def show_reservations(filename):
with open(filename) as f:
for line in f.readlines():
line = line.replace(',', '').split()
status = line[2]
if status == "CONFIRMED":
name = line[0]
time = line[1]
print(name + ",", time)
However, calling my solution on the example file above gives me following output:
show_reservations("reservations.txt")
>>> Alex, 20
William, 18
What to do?
you don't store your data and you also need some sorting
def funct(e):
return e['time']
def show_reservations(filename):
with open(filename) as f:
l=[]
for line in f.readlines():
line = line.replace(',', '').split()
dict={}
status = line[2]
if status == "CONFIRMED":
dict["name"] = line[0]
dict["time"] = line[1]
name = line[0]
time = line[1]
l.append(dict)
l.sort(key=funct)
for i in l:
print('{0} , {1}'.format(i["name"],i["time"]))
show_reservations("input.txt")
It happens because your original sequence comes in this way:
Alex, 20, CONFIRMED
...
William, 18, CONFIRMED
So you can save your filtered elements into a list and apply sorting on it. For example using sorted function.
You could try something like this:
def show_reservations(filename):
confirmed_orders = []
with open(filename) as f:
for line in f.readlines():
line = line.replace(',', '').split()
name, _time, status = line
if status == "CONFIRMED":
confirmed_orders.append((name, _time))
confirmed_orders_by_time = sorted(confirmed_orders, key=lambda x: x[1])
for name, _time in confirmed_orders_by_time:
print(name + ",", _time)
Also several additional suggestions in case the snippet you've provided is a real production code:
time is a bad name for variable because it can clash with built-in Python's module time.
split gives you tuple, so instead of messing with accessing by index you can unpack it:
name, _time, status = line
This thing line.replace(',', '').split() won't work correctly if name or status in the file will have a "space". Consider to use csv or something else for parsing data file.
If you use Python 3.5 or higher f-string is a preferable way instead of manual string concatenation:
print(f"{name}, {_time}")
def show_reservations(filename):
reservations = []
with open(filename) as f:
for line in f.readlines():
splitted_line = line.replace(',', '').split()
status = splitted_line[2]
if status == "CONFIRMED":
time = splitted_line[1]
name = splitted_line[0]
reservations.append({"time":time, "name":name})
return sorted(reservations, key=lambda k: k['time'])
for reservation in show_reservations("reservations.txt"):
print(reservation["name"] + ",", reservation["time"])
Instead of directly printing, append the entries to a list of tuples (time, name). Then after the list, sort it (li.sort()), and loop through it again, this time printing.
I am trying to convert multiple .txt file to "table-like" data (with columns and rows). Each .txt file should be considered as a new column.
Consider below content of the .txt file:
File1.txt
Hi there
How are you doing?
What is your name?
File2.txt
Hi
Great!
Oliver, what's yours?
I have created a simple method, that accepts the file and and integer (the file number from another method):
def txtFileToJson(text_file, column):
data = defaultdict(list)
i = int(1)
with open(text_file) as f:
data[column].append(column)
for line in f:
i = i + 1
for line in re.split(r'[\n\r]+', line):
data[column] = line
with open("output.txt", 'a+') as f:
f.write(json.dumps(data))
So above method will run two times (one time for each file, and append the data).
This is the output.txt file after I have run my script:
{"1": "What is your name?"}{"2": "Oliver, what's yours?"}
As you can see, I can only get it to create a new for each file I have, and then add the entire line.
[{
"1": [{
"1": "Hi there",
"2": "How are you doing?",
"3": "\n"
"4": "What is your name?"
},
"2": [{
"1": "Hi"
"2": "Great!",
"3": "\n",
"4": "Oliver, what's yours?"
},
}]
Update:
OK, so I played around a bit and got a bit closer:
myDict = {str(column): []}
i = int(1)
with open(text_file) as f:
for line in f:
# data[column].append(column)
match = re.split(r'[\n\r]+', line)
if match:
myDict[str(column)].append({str(i): line})
i = i + 1
with open(out_file, 'a+') as f:
f.write(json.dumps(myDict[str(column)]))
That gives me below output:
[{"1": "Hi there\n"}, {"2": "How are you doing?\n"}, {"3": "\n"}, {"4": "What is your name?"}]
[{"1": "Hi\n"}, {"2": "Great!\n"}, {"3": "\n"}, {"4": "Oliver, what's yours?"}]
But as you can see, now I have multiple JSON root elements.
Solution
Thanks to jonyfries, I did this:
data = defaultdict(list)
for path in images.values():
column = column + 1
data[str(column)] = txtFileToJson(path, column)
saveJsonFile(path, data)
And then added a new method to save the final combined list:
def saveJsonFile(text_file, data):
basename = os.path.splitext(os.path.basename(text_file))
dir_name = os.path.dirname(text_file) + "/"
text_file = dir_name + basename[0] + "1.txt"
out_file = dir_name + 'table_data.txt'
with open(out_file, 'a+') as f:
f.write(json.dumps(data))
You're creating a new dictionary within the function itself. So each time you pass a text file in it will create a new dictionary.
The easiest solution seems to be returning the dictionary created and add it to an existing dictionary.
def txtFileToJson(text_file, column):
myDict = {str(column): []}
i = int(1)
with open(text_file) as f:
for line in f:
# data[column].append(column)
match = re.split(r'[\n\r]+', line)
if match:
myDict[str(column)].append({str(i): line})
i = i + 1
with open(out_file, 'a+') as f:
f.write(json.dumps(myDict[str(column)]))
return myDict
data = defaultdict(list)
data["1"] = txtFileToJson(text_file, column)
data["2"] = txtFileToJson(other_text_file, other_column)
def read(text_file):
data, i = {}, 0
with open(text_file) as f:
for line in f:
i = i + 1
data['row_%d'%i] = line.rstrip('\n')
return data
res = {}
for i, fname in enumerate([r'File1.txt', r'File2.txt']):
res[i] = read(fname)
with open(out_file, 'w') as f:
json.dump(res, f)
First, if I understand you are trying to get as output a dictionary of dictionaries, then let me observe that what I understand to be your desired output seems to be enclosing the whole thing within a list, Furthermore, you have unbalanced open and closed list brackets within the dictionaries, which I will ignore, as I will the enclosing list.
I think you need something like:
#!python3
import json
import re
def processTxtFile(text_file, n, data):
d = {}
with open(text_file) as f:
i = 0
for line in f:
for line in re.split(r'[\n\r]+', line):
i = i + 1
d[str(i)] = line
data[str(n)] = d
data = dict()
processTxtFile('File1.txt', 1, data)
processTxtFile('File2.txt', 2, data)
with open("output.txt", 'wt') as f:
f.write(json.dumps(data))
If you really need the nested dictionaries to be enclosed within a list, then replace
data[str(n)] = d
with:
data[str(n)] = [d]
I want to know, if it's possible to save the output of this code into a dictionary (maybe it's also the wrong data-type). I'm not expirienced in coding yet, so I can't think of a way it could work.
I want to create a dicitionary that has the lines of the txt.-file in it alongside the value of the corresponding line. In the end, I want to create a code, where the user has the option to search for a word in the line through an input - the output should return the corresponding line. Has anyone a suggestion? Thanks in advance! Cheers!
filepath = 'myfile.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
This should do it (using the code you provided as a framework, it only takes one extra line to store it in a dictionary):
my_dict={}
filepath = 'myfile.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
# print("Line {}: {}".format(cnt, line.strip()))
my_dict[str(line.strip())] = cnt
line = fp.readline()
cnt += 1
Then, you can prompt for user input like this:
usr_in = input('enter text to search: ')
print('That text is found at line(s) {}'.format(
[v for k,v in my_dict.items() if usr_in in k]))
For storing the line string value as key in dictionary and line number as value, you can try something like:
filepath = 'myfile.txt'
result_dict = {}
with open(filepath) as fp:
for line_num, line in enumerate(fp.readlines()):
result_dict[line.strip()] = line_num+1
Or, using dictionary comprehension, above code can be:
filepath = 'myfile.txt'
with open(filepath) as fp:
result_dict = {line.strip(): line_num+1
for line_num, line in enumerate(fp.readlines())}
Now to search and return all the lines with words:
search_result = [{key: value} for key, value in result_dict.items()
if search_word in key]
if the file for example contains:
A: GHJIG
B: AHYFASF
C: IYDDFG
f = open(example.txt)
I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.
input: A
output: GHJIG
how to do it?
Try this:
with open('test.txt','r') as file:
content = file.readlines()
my_dict = {}
for line in content:
split = line.split(':')
my_dict[split[0]] = split[1]
input = raw_input("Choose a letter")
if input in my_dict:
print my_dict[input]
It would be better to use a OrderedDict from collections, because default dictionary has a not a precise order.
Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.
with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
content = file_obj.readlines()
sample_dict = {}
for value in content:
sample_dict[value.split(':')[0]] = value.split(':')[1]
input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")
I have a plain text file with some data in it, that I'm trying to open and read using a Python (ver 3.2) program, and trying to load that data into a data structure within the program.
Here's what my text file looks like (file is called "data.txt")
NAME: Joe Smith
CLASS: Fighter
STR: 14
DEX: 7
Here's what my program looks like:
player_name = None
player_class = None
player_STR = None
player_DEX = None
f = open("data.txt")
data = f.readlines()
for d in data:
# parse input, assign values to variables
print(d)
f.close()
My question is, how do I assign the values to the variables (something like setting player_STR = 14 within the program)?
player = {}
f = open("data.txt")
data = f.readlines()
for line in data:
# parse input, assign values to variables
key, value = line.split(":")
player[key.strip()] = value.strip()
f.close()
now the name of your player will be player['name'], and the same goes for all other properties in your file.
import re
pattern = re.compile(r'([\w]+): ([\w\s]+)')
f = open("data.txt")
v = dict(pattern.findall(f.read()))
player_name = v.get("name")
plater_class = v.get('class')
# ...
f.close()
The most direct way to do it is to assign the variables one at a time:
f = open("data.txt")
for line in f: # loop over the file directly
line = line.rstrip() # remove the trailing newline
if line.startswith('NAME: '):
player_name = line[6:]
elif line.startswith('CLASS: '):
player_class = line[7:]
elif line.startswith('STR: '):
player_strength = int(line[5:])
elif line.startswith('DEX: '):
player_dexterity = int(line[5:])
else:
raise ValueError('Unknown attribute: %r' % line)
f.close()
That said, most Python programmers would stored the values in a dictionary rather than in variables. The fields can be stripped (removing the line endings) and split with: characteristic, value = data.rstrip().split(':'). If the value should be a number instead of a string, convert it with float() or int().