I was not clear enough in my last question, and so I'll explain my question more this time.
I am creating 2 separate programs, where the first one will create a text file with 2 generated numbers, one on line 1 and the second on line 2.
Basically I saved it like this:
In this example I'm not generating numbers, just assigning them quickly.
a = 15
b = 16
saving = open('filename.txt', "w")
saving.write(a+"\n")
saving.write(b+"\n")
saving.close()
Then I opened it on the next one:
opening = open('filename.txt', "w")
a = opening.read()
opening.close()
print(a) #This will print the whole document, but I need each line to be differnet
Now I got the whole file loaded into 'a', but I need it split up, which is something that i have not got a clue on how to do. I don't believe creating a list will help, as I need each number (Variables a and b from program 1) to be different variables in program 2. The reason I need them as 2 separate variables is because I need to divide it by a different number. If I do need to do a list, please say. I tried finding an answer for about an hour in total, though I couldn't find anything.
The reason I can't post the whole program is because I haven't got access to it from here, and no, this is not cheating as we are free to research and ask questions outside the classroom, if someone wonders about that after looking at my previous question.
If you need more info please put it in a comment and I'll respond ASAP.
opening = open('filename.txt') # "w" is not necessary since you're opening it read-only
a = [b.split() for b in opening.readlines()] # create a list of each line and strip the newline "\n" character
print(a[0]) # print first line
print(a[1]) # print second line
Related
I'm working on a project in my work using purely Python 3:
If I take my scanner, (Because I work in inventory) and anything I scan goes into a text doc, and I scan the location "117" , and then I scan any device in any other location, (the proceeding lines in the text doc "100203") and I run the script and it plugs in '117' in the search on our database and changes each of the devices (whether they were assigned to that location or not) into that location, (Validating those devices are in location '117')
My main question is the 3rd objective down from the Objectives list below that doesn't have "Done" after it.
Objective:
Pull strings from a text document, convert it into a dictionary. = (Text_Dictionary) **Done**
Assign the first var in the dictionary to a separate var. = (First_Line) **Done**
All proceeding var's greater then the first var in the dictionary should be passed into a function individually. = (Proceeding_Lines)
Side note: The code should loop in a fashion that should (.pop) the var from the dictionary/list, But I'm open for other alternatives. (Not mandatory)
What I already have is:
Project.py:
1 import re
2 import os
3 import time
4 import sys
5
6 with open(r"C:\Users\...\text_dictionary.txt") as f:
7 Text_Dictionary = [line.rstrip('\n') for line in
8 open(r"C:\Users\...\text_dictionary.txt")]
9
10 Text_Dict = (Text_Dictionary)
11 First_Line = (Text_Dictionary[0])
12
13 print("The first line is: ", First_Line)
14
15 end = (len(Text_Dictionary) + 1)
16 i = (len(Text_Dictionary))
17
What I have isn't much on the surface, but I have another "*.py" file fill of code that I am going to copy in for the action that I wish to preform on each of the vars in the Text_Dictionary.txt. Lines 15 - 16 was me messing with what I thought might solve this.
In the imported text document, the var's look very close to this (Same length)(All digits):
Text_Dictionary.txt:
117
23000
53455
23454
34534
...
Note: These values will change for each time the code is ran, meaning someone will type/scan in these lines of digits each time.
Explained concept:
Ideally, I would like to have the first line point towards a direction, and the rest of the digits would follow; however, each (Example: '53455') needs to be ran separately then the next in line and (Example: '117') would be where '53455' goes. You could say the first line is static throughout the code, unless otherwise changed inText_Dictionary.txt. '117'is ran in conjunction with each iteration proceeding it.
Background:
This is for inventory management for my office, I am in no way payed for doing this, but it would make my job a heck-of-a-lot easier. Also, I know basic python to get myself around, but this kinda stumped me. Thank you to whoever answers!
I've no clue what you're asking, but I'm going to take a guess. Before I do so, your code was annoying me:
with open("file.txt") as f:
product_ids = [line.strip() for line in f if not line.isspace()]
There. That's all you need. It protects against blank lines in the file and weird invisible spaces too, this way. I decided to leave the data as strings because it probably represents an inventory ID, and in the future that might be upgraded to "53455-b.42454#62dkMlwee".
I'm going to hazard a guess that you want to run different code depending on the number at the top. If so, you can use a dictionary containing functions. You said that you wanted to run code from another file, so this is another_file.py:
__all__ = ["dispatch_whatever"]
dispatch_whatever = {}
def descriptive_name_for_117(product_id):
pass
dispatch_whatever["117"] = descriptive_name_for_117
And back in main_program.py, which is stored in the same directory:
from another_file import dispatch_whatever
for product_id in product_ids[1:]:
dispatch_whatever[product_ids[0]](product_id)
I'm pretty new to Python! I recently started coding a program which I want to write and read to and from text files, while compressing/decompressing sentences (sort of).
However, I've run into a couple problems which I can't seem to fix, basically, I've managed to code the compressing section. But when I go to read the contents of the text file, I'm not sure how to recreate the original sentence through the positions and unique words?!
###This section will compress the sentence(s)###
txt_file = open("User_sentences.txt","wt")
user_sntnce = input(str("\nPlease enter your sentences you would like compressed."))
user_sntnce_list = user_sntnce.split(" ")
print(user_sntnce_list)
for word in user_sntnce_list:
if word not in uq_words:
uq_words.append(word)
txt_file.write(str(uq_words) + "\n")
for i in user_sntnce_list:
positions = int(uq_words.index(i) + 1)
index.append(positions)
print(positions)
print(i)
txt_file.write(str(positions))
txt_file.close()
###This section will DECOMPRESS the sentence(s)###
if GuideChoice == "2":
txt_file = open("User_sentences.txt","r")
contents = txt_file.readline()
words = eval(contents)
print(words)
txt_file.close()
This is my code so far, it seems to work, however as I've said I'm really stuck, and I really don't know how to move on and recreate the original sentence from the text file.
From what understand you want to substitute each word in a text file with a word of your choice (a shorter one if you want to "compress"). Meanwhile you keep a "dictionary" (not in the python sense) uq_words where you associate each different word with an index.
So a sentence "today I like pizza, today is like yesterday" will become:
"12341536".
I tried your code removing if GuideChoice == "2": and defining uq_words=[] and index=[].
If that's what you intend to do then:
I imagine you are calling this compression from time to time, it's in a function. So doing what you do in the second line is to open a NEW file with the same name of the previous ones, meaning you will always have the last sentence compressed, loosing the previous.
Try to read every time the lines, rewrite all and add the new (kinda what you did in contents = txt_file.readline().
You are printing both the compressed translation (like "2345") AND the array whose component are the words of the splitted sentence. I do not think that is the "compressed" document you are aiming for. Just the "2345" part, right?
Since, I believe, you want to keep a dictionary, but this code is inside a function, you will loose the dictionary every time the function ends. So write 2 documents: one with the compressed text (every time refreshed and not rewritten!) and another file with 2 columns, where you write the dictionary. You pass the dictionary file name as a string to the function, so you can update it in case new words are added, and you read it as a NX2 array (N the number of words).
I am trying to learn Python by doing.
Aim of the code below: To form a part of a larger file in which I will be checking if all info i.e. Address, email add, contact person etc is updated in a list (I am not sure whether to use lists, arrays or dictionary?). If yes I want it to give options to do various things for the customer etc.
The code below is basically checking whether a customer exists in the list. If not, it is supposed to add the customer name in c to the list.
When I run the program it works. But as soon as I restart the program the last added, i.e. if I entered the customer as: ABC in the last run of the program, is not in the list.
Can someone point me in the right direction on this? Also can I pass the values in the list onto multiple dictionaries as keys for further values to be added i.e. email address etc?
customer = ['GMS']
print ("Enter Customer Name:")
c = input()
if c in customer:
print ("Customer Exsists")
else:
customer.append(c)
print ("Added to list")
Your program is fine as far as it goes. It does input, and it does
append to the list.
However, all the data in the program will go away as soon as the program
exits. The only way to retain information across runs is to save the
information in some kind of persistent storage. As Rok Novosel mentions
in the comment, this can be done with the pickle module, though as a
beginner, you might want to defer that until later.
At this stage of your learning, I’d recommend looking at file
operations: opening and closing, reading and writing. For a single list
like this, the writelines() and readlines() file methods would be
the simplest way to save and restore, respectively.
As for your dictionary question: yes, since you’re making sure the
customer names are unique, you can use them as dictionary keys. Storing
that data would be more complicated; you could use pickle, or work out
a file structure to parse on input.
Q1: Your data resides in memory during one execution instance. When the program exits, the memory is freed and your data is not automatically stored elsewhere. You may use a format you like to store it onto the disk where data is persistent. Simply writing to a file could work for you at this moment of your learning.
Q2: Yes, you may use a dictionary.
Open file and read it in list
with open('file', 'r') as f:
customers = list(f)
f.close()
Do whatever You want to list. Then write to file.
To persist customers on HDD.
with open('file', 'w') as f:
for l in f:
f.write(str(l) + '\n')
f.close()
I'm fairly new to python, but I'm making a script and I want one of the functions to update a variable from another file. It works, but when I exit the script and reload it, the changes aren't there anymore. For example (this isn't my script):
#File: changeFile.txt
number = 0
#File: changerFile.py
def changeNumber():
number += 1
If I retrieve number during that session, it will return 1, but if I exit out and go back in again and retrieve number without calling changeNumber, it returns 0.
How can I get the script to actually save the number edited in changeNumber to changeFile.txt? As I said, I'm fairly new to python, but I've looked just about everywhere on the Internet and couldn't really find an answer that worked.
EDIT: Sorry, I forgot to include that in the actual script, there are other values.
So I want to change number and have it save without deleting the other 10 values stored in that file.
Assuming, as you show, that changeFile.txt has no other content whatever, then just change the function to:
def changeNumber():
global number # will not possibly work w/o this, the way you posted!
number += 1
with open('changeFile.txt', 'w') as f:
f.write('number = {}\n'.format(number))
ADDED: the OP edited the Q to mention (originally omitted!-) the crucial fact that changefile.txt has other lines that need to be preserved as well as the one that needs to be changed.
That, of course, changes everything -- but, Python can cope!-)
Just add import fileinput at the start of this module, and change the last two lines of the above snippet (starting with with) to:
for line in fileinput.input(['changefile.txt'], inplace=True):
if line.startswith('number ');
line = 'number = {}\n'.format(number)'
print line,
This is the Python 2 solution (the OP didn't bother to tell us if using Py2 or Py3, a crucial bit of info -- hey, who cares about making it easy rather than very hard for willing volunteers to help you, right?!-). If Python 3, change the last statement from print line, to
print(line, end='')
to get exactly the same desired effect.
I need to write a program like this:
Write a program that reads a file .picasa.ini and copies pictures in new files, whose names are the same as identification numbers of person on these pictures (eg. 8ff985a43603dbf8.jpg). If there are more person on the picture it makes more copies. If a person is on more pictures, later override earlier copies of pictures; if a person 8ff985a43603dbf8 may appear in more pictures, only one file with this name will exist. You must presume that we have a simple file .picasa.ini.
I have an .ini, that consists:
[img_8538.jpg]
faces=rect64(4ac022d1820c8624),**d5a2d2f6f0d7ccbc**
backuphash=46512
[img_8551.jpg]
faces=rect64(acb64583d1eb84cb),**2623af3d8cb8e040**;rect64(58bf441388df9592),**d85d127e5c45cdc2**
backuphash=8108
...
Is this a good way to start this program?
for line in open('C:\Users\Admin\Desktop\podatki-picasa\.picasa.ini'):
if line.startswith('faces'):
line.split() # what must I do here to split the bolded words?
Is there a better way to do this? Remember the .jpg file must be created with a new name, so I think I should link the current .jpg file with the bolded one.
Consider using ConfigParser. Then you will have to split each value by hand, as you describe.
import ConfigParser
import string
config = ConfigParser.ConfigParser()
config.read('C:\Users\Admin\Desktop\podatki-picasa\.picasa.ini')
imgs = []
for item in config.sections():
imgs.append(config.get(item, 'faces'))
This is still work in progress. Just want to ask if it's correct.
edit:
Still don't know hot to split the bolded words out of there. This split function really is a pain for me.
Suggestions:
Your lines don't start with 'faces', so your second line won't work the way you want it to. Depending on how the rest of the file looks, you might only need to check whether the line is empty or not at that point.
To get the information you need, first split at ',' and work from there
Try at a solution: The elements you need seem to always have a ',' before them, so you can start by splitting at the ',' sign and taking everything from the 1-index elemnt onwards [1::] . Then if what I am thinking is correct, you split those elements twice again: at the ";" and take the 0-index element of that and at that " ", again taking the 0-index element.
for line in open('thingy.ini'):
if line != "\n":
personelements = line.split(",")[1::]
for person in personelements:
personstring = person.split(";")[0].split(" ")[0]
print personstring
works for me to get:
d5a2d2f6f0d7ccbc
2623af3d8cb8e040
d85d127e5c45cdc2