How to print more variables into file? - python-3.x

I know how to print one value of variable but I have a problem with more variables into one line.
file = open("values","w+")
file.write(str(q+q_krok+omega+omega_krok+e+e_krok))
The desired files values:
1-8-9-9-6-6
I would like to print values of 6 variables into file and between them put some value, for instance -. Thank you

Put the values into a string, then simply write that string to file.
values = <whatever your values are, as a string>
with open(“values.txt”, “w”) as f:
f.write(values)
If you have a list of values, you could create the string by using a join statement.
val_list = [1, 2, 3, 4, 5]
values = '-'.join(val_list)
If you have a specific set of values stored in different vars, you could use an f-string.
values = f'{val1}-{val2}-{val3}-{val4}'

Try doing it this way:
li = [q,q_krok,omega,omega_krok,e,e_krok]
values = '-'.join(li)
with open("values_file", "w") as f:
f.write(values)
You can even do it this way:
file = open("values_file","w+")
file.write(values)

You can have the values into a list, like:
items = [1,8,9,9,6,6]
with open('test.txt, 'r') as f:
for elem in items[:-1]: -- for each element instead of last
print(elem, end="-") -- print the value and the separator
if (len(items) > 1):
print(items[-1]) -- print last item without separator
A very well-made tutorial about reading/writing to files in python can be watched here:
https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=1264s

Related

Create a string from a list using list comprehension

I am trying to create a string separated by comma from the below given list
['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
New string should contain only the filename like below which is separated by comma
'aaa.xlsx,bbb.xlsx,ccc.xlsx'
I have achieved this using the below code
n = []
for p in input_list:
l = p.split('\\')
l = l[len(l)-1]
n.append(l)
a = ','.join(n)
print(a)
But instead of using multiple lines of code i would like to achieve this in single line using a list comprehension or regular expression.
Thanks in advance...
Simply do a
main_list = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print([x.split("\\")[-1] for x in main_list])
OUTPUT:
['aaa.xlsx', 'bbb.xlsx', 'ccc.xlsx']
In case u want to get the string of this simply do a
print(",".join([x.split("\\")[-1] for x in main_list]))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Another way to do the same is:
print(",".join(map(lambda x : x.split("\\")[-1],main_list)))
OUTPUT:
aaa.xlsx,bbb.xlsx,ccc.xlsx
Do see that os.path.basename is OS-dependent and may create problems on cross-platform scripts.
Using os.path.basename with str.join
Ex:
import os
data = ['D:\\abc\\pqr\\123\\aaa.xlsx', 'D:\\abc\\pqr\\123\\bbb.xlsx', 'D:\\abc\\pqr\\123\\ccc.xlsx']
print(",".join(os.path.basename(i) for i in data))
Output:
aaa.xlsx,bbb.xlsx,ccc.xlsx

Python 3 - files imported as dictionary, but the values are lists - how to resolve?

I'm importing files from a folder into python as a dictionary, with the
key = filename and value = file contents.
e.g.,
mydict = {'File1': ['this is a string as a list'],
'File2': ['second string in file 2 is also a list']}
Whereas what I'd like is to have:
mydict = {'File1': 'this is a string as a list', 'File2:': '...'}
I also want to count the following strings: "string", "this is", "second string" to output it in a datastructure. I'm guessing I'd need to use counter from collections to do that - but do I first need to tokenize my values?
Code to import text into dictionary:
filenames = os.listdir('.')
file_dict = {}
for file in filenames:
with open(file) as f:
items = [i.strip() for i in f.read().split(",")]
file_dict[file.replace(".txt", "")] = items
print(file_dict)
To make the values all lowercase (doesn't work since they are in list):
#convert dictionary to lower case
def lower_dict(d):
new_dict = dict((k, v.lower()) for k, v in d.items())
return new_dict
print(lower_dict(file_dict))
AttributeError: 'list' object has no attribute 'lower'
Any help is greatly appreciated.
You are splitting the input when you load it:
items = [i.strip() for i in f.read().split(",")]
If you want just the file contents, then you can just use:
items = f.read()
If you still want to trim whitespaces around commas (,), then you can recombine them with str.join
items = ','.join([i.strip() for i in f.read().split(",")]) # This will reinsert commas
items = ''.join([i.strip() for i in f.read().split(",")]) # This will not

Writing a list to a file and reading it back

I am a beginner and I have searched for my answer in this forum, and have tried to follow examples (many are more complex than I can understand at this point). I want to write my list, Variables, to a file and read it back when necessary.
a = 'M'
b = 456.78
c = 100
Variables = [a, b, c]
f = open("test5.txt", "w")
with open("test5.txt", "r") as opened_file:
for variable in Variables:
"test5.txt".write(variable, '\n')
I get a "AttributeError" 'str' object has no attribute 'write'
What do I change?
How would i read it back?
The error means you can't write to a string, instead you want to write to the opened file. Change the string test5.txt to the file you've opened f:
for variable in Variables:
f.write("%s\n" % variable)
f.close()
then read it back:
with open("test5.txt", "r") as opened_file:
variables = opened_file.readlines()
print(variables) #will print the file contents
Edit: as discussed in the comments, the original request to re-assign the values to the appropriate variable names is not possible, the next best option would be to assign each value read from the file to their indices in the original list. Unfortunately the original datatypes are lost, keeping only the string value.
for i in range(len(variables)):
Variables[i] = variables[i].strip()
print(Variables) # ['M', '456.78', '100']

Merge Two wordlists into one file

I have two wordlists, as per examples below:
wordlist 1 :
code1
code2
code3
wordlist 2 :
11
22
23
I want to take wordlist 2 and put every number in a line with first line in wordlist 1
example of the output :
code111
code122
code123
code211
code222
code223
code311
.
.
Can you please help me with how to do it? Thanks!
You can run two nested for loops to iterate over both lists, and append the concatenated string to a new list.
Here is a little example:
## create lists using square brackets
wordlist1=['code1', ## wrap something in quotes to make it a string
'code2','code3']
wordlist2=['11','22','23']
## create a new empty list
concatenated_words=[]
## first for loop: one iteration per item in wordlist1
for i in range(len(wordlist1)):
## word with index i of wordlist1 (square brackets for indexing)
word1=wordlist1[i]
## second for loop: one iteration per item in wordlist2
for j in range(len(wordlist2)):
word2=wordlist2[j]
## append concatenated words to the initially empty list
concatenated_words.append(word1+word2)
## iterate over the list of concatenated words, and print each item
for k in range(len(concatenated_words)):
print(concatenated_words[k])
list1 = ["text1","text2","text3","text4"]
list2 = [11,22,33,44]
def iterativeConcatenation(list1, list2):
result = []
for i in range(len(list2)):
for j in range(len(list1)):
result = result + [str(list1[i])+str(list2[j])]
return result
have you figured it out? depends on if you want to input the names on each list, or do you want it to for instance automatically read then append or extend a new text file? I am working on a little script atm and a very quick and simple way, lets say u want all text files in the same folder that you have your .py file:
import os
#this makes a list with all .txt files in the folder.
list_names = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]
for file_name in list_names:
with open(os.getcwd() + "/" + file_name) as fh:
words = fh.read().splitlines()
with open(outfile, 'a') as fh2:
for word in words:
fh2.write(word + '\n')

Python read file contents into nested list

I have this file that contains something like this:
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
And I need to read it into a 2D list so it looks like this:
[[O,O,O,O,O,O,X,O,O,O,O],[O,O,O,O,O,X,O,O,O,O,O],[O,O,O,O,X,O,O,O,O,O,O],[X,X,O,O,X,O,O,O,O,O,O],[X,X,X,X,O,O,O,O,O,O,O,O],[O,O,O,O,O,O,O,O,O,O,O]
I have this code:
ins = open(filename, "r" )
data = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
numbers = [(n) for n in number_strings]
data.append(numbers) # Add the "row" to your list.
return data
But it doesn't seem to be working because the O's and X's do not have spaces between them. Any ideas?
Just use data.append(list(line.rstrip())) list accepts a string as argument and just splits them on every character.

Resources