This program must change the last parameter on a line based on the starting code.
File now:
312|fotelja snesko|bela|15|2900|fotelja|False
621|digimon tabure|crna|25|850|tabure|False
Code is:>> 312
File after:
312|fotelja snesko|bela|15|2900|fotelja|True
621|digimon tabure|crna|25|850|tabure|False
My work right now.
parameter = input("\nCode is >> ")
with open("komad_namestaja.txt", "r") as fileNAME:
allDATA = fileNAME.readlines()
for linija in allDATA:
linija = linija.split("|")
if parameter == linija[0]:
linija[6] = "True"
With this I read every line in the file and found the line that I need. I just need to change False to True in that line. How can I change it?
As, your file is not too large(let's say 1 GB), no need of a temporary file. Below solution can help you. The idea is to:
Convert the file contents to a list
Split the innerLists
modify the list based on your condition
form the innerLists
finally writing it back to the same file.
open mode should be r+, so that it can both read and write to the file.
Let's see the code below:
with open('komad_namestaja.txt','r+') as f:
data = f.readlines()
output_data=[]
for i in data:
lst=i.split("|")
if(lst[0]=='312'):
lst[-1]='True\n'
output_data.append("|".join(lst))
f.seek(0)
f.writelines(output_data)
What you need to do is open a temporary file, write your result to that file and then replace the old file with your new file:
fh, abs_path = mkstemp() # Create a temporary file
with open(abs_path,'w') as new_file:
with open("komad_namestaja.txt", "r") as old_file:
for line in old_file:
linija = linija.split("|")
if parameter == linija[0]:
linija[6] = "True"
new_file.write(linija)
close(fh)
remove("komad_namestaja.txt") # Remove original file
move(abs_path, "komad_namestaja.txt") # Move new file to old file location
Related
trying to replace whole line if it matches with specefic character but getting an error below as io.UnsupportedOperation: not readable
trying to replace if "date=datetime(" exists then replace the complete line (in the file) with something : date=datetime(2020, 1, 1)
pls anyone suggest.
Sampledata: /home/arya/config.txt
/home/file.txt,date=datetime(2020, 1, 1)
/home/file2.txt,date=datetime(2020, 1, 20)
for variable in open("/home/arya/config.txt","r"):
filename=variable.rstrip('\n').split(',')[0]
replaceval=variable.rstrip('\n').split(',')[1]
outFile = open(filename,'w')
for line in outFile:
if "date=datetime(" in line:
line=replaceval
outFile.write(line)
Error : io.UnsupportedOperation: not readable
content of /home/file.txt
import os
date=datetime(2099, 1, 1) ## this value may change in each file
trying to get something like below after replace
import os
date=datetime(2020, 1, 1)
outfile is being opened with the 'w' flag, which means a new file is opened and there's nothing to iterate over.
for variable in open("/home/arya/config.txt", "r"):
filename = variable.rstrip("\n").split(",")[0]
replaceval = variable.rstrip("\n").split(",")[1]
originalContents = open(filename, "r").readlines()
outfile = open(filename, "w")
for line in originalContents:
if "date=datetime(" in line:
line = replaceval
outFile.write(line)
This will set the original contents to the variable originalContents using the readlines() method, this returns a list of all lines in the original file.
Then the same filename is opened with the 'w' flag, which overwrites it. The new contents are then written to it. The contents of line are modified as needed.
I am very new with python. I have a .txt file and want to convert it to a .csv file with the format I was told but could not manage to accomplish. a hand can be useful for it. I am going to explain it with screenshots.
I have a txt file with the name of bip.txt. and the data inside of it is like this
I want to convert it to csv like this csv file
So far, what I could do is only writing all the data from text file with this code:
read_files = glob.glob("C:/Users/Emrehana1/Desktop/bip.txt")
with open("C:/Users/Emrehana1/Desktop/Test_Result_Report.csv", "w") as outfile:
for f in read_files:
with open(f, "r") as infile:
outfile.write(infile.read())
So is there a solution to convert it to a csv file in the format I desire? I hope I have explained it clearly.
There's no need to use the glob module if you only have one file and you already know its name. You can just open it. It would have been helpful to quote your data as text, since as an image someone wanting to help you can't just copy and paste your input data.
For each entry in the input file you will have to read multiple lines to collect together the information you need to create an entry in the output file.
One way is to loop over the lines of input until you find one that begins with "test:", then get the next line in the file using next() to create the entry:
The following code will produce the split you need - creating the csv file can be done with the standard library module, and is left as an exercise. I used a different file name, as you can see.
with open("/tmp/blip.txt") as f:
for line in f:
if line.startswith("test:"):
test_name = line.strip().split(None, 1)[1]
result = next(f)
if not result.startswith("outcome:"):
raise ValueError("Test name not followed by outcome for test "+test_name)
outcome = result.strip().split(None, 1)[1]
print test_name, outcome
You do not use the glob function to open a file, it searches for file names matching a pattern. you could open up the file bip.txt then read each line and put the value into an array then when all of the values have been found join them with a new line and a comma and write to a csv file, like this:
# set the csv column headers
values = [["test", "outcome"]]
current_row = []
with open("bip.txt", "r") as f:
for line in f:
# when a blank line is found, append the row
if line == "\n" and current_row != []:
values.append(current_row)
current_row = []
if ":" in line:
# get the value after the semicolon
value = line[line.index(":")+1:].strip()
current_row.append(value)
# append the final row to the list
values.append(current_row)
# join the columns with a comma and the rows with a new line
csv_result = ""
for row in values:
csv_result += ",".join(row) + "\n"
# output the csv data to a file
with open("Test_Result_Report.csv", "w") as f:
f.write(csv_result)
Hi I already have the search function sorted out:
def searchconfig():
config1 = open("config.php", "r")
b='//cats'
for num, line in enumerate(config1,0):
if b in line:
connum = num + 1
return connum
config1.close()
This will return the line number of //cats, I then need to take the data underneath it put it in a tempoary document, append new data under the //cats and then append the data in the tempoary document to the original? how would i do this? i know that i would have to use 'a' instead of 'r' when opening the document but i do not know how to utilise the line number.
I think, the easiest way would be to read the whole file into a list of strings, work on that list and write it back afterwards.
# Read all lines of the file into a list of strings
with open("config.php", "r") as file:
lines = list(file)
file.close()
# This gets the line number for the first line containing '//cats'
# Note that it will throw an StopIteration exception, if no such line exists...
linenum = (num for (num, line) in enumerate(lines) if '//cats' in line).next()
# insert a line after the line containing '//cats'
lines.insert(linenum+1, 'This is a new line...')
# You could also replace the line following '//cats' like
lines[linenum+1] = 'New line content...'
# Write back the file (in fact this creates a new file with new content)
# Note that you need to append the line delimiter '\n' to every line explicitely
with open("config.php", "w") as file:
file.writelines(line + '\n' for line in lines)
file.close()
Using "a" as mode for open would only let you append ath the end of the file.
You could use "r+" for a combined read/write mode, but then you could only overwrite some parts of the file, there is no simple way to insert new lines in the middle of the file using this mode.
You could do it like this. I am creating a new file in this example as it is usually safer.
with open('my_file.php') as my_php_file:
add_new_content = ['%sNEWCONTENT' %line if '//cat' in line
else line.strip('\n')
for line in my_php_file.readlines()]
with open('my_new_file.php', 'w+') as my_new_php_file:
for line in add_new_content:
print>>my_new_php_file, line
Question:
How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?
I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.
Thanks
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
I think this is exactly what you need:
file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)
I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.
EDIT: You can just assign an input to a variable...
filename = input('Enter file path: ')
And then the above stuff, except open the file using that variable as a parameter...
file = open(filename, 'r')
Finally, submit the list lines to your function, selectionSort.
selectionSort(lines)
Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.
Easiest way to open a file in Python and store its contents in a string:
with open('file.txt') as f:
contents = f.read()
for your problem:
with open('file.txt') as f:
values = [int(line) for line in f.readlines()]
print values
Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.
You can assign the list of integers to a string or a list
file = open('file.txt', mode = 'r')
values = file.read()
values will have a string which can be printed directly
file = open('file.txt', mode = 'r')
values = file.readlines()
values will have a list for each integer but can't be printed directly
f.readlines() read all the lines in your file, but what if your file contains a lot of lines?
You can try this instead:
new_list = [] ## start a list variable
with open('filename.txt', 'r') as f:
for line in f:
## remove '\n' from the end of the line
line = line.strip()
## store each line as an integer in the list variable
new_list.append(int(line))
print new_list
I am currently having problems displaying a file correctly once i have written a dictionary to the file. For this program the input file needs to have the format:
ID: Date: Dayskept: ProductName e.g. 1:12/12/2011:12:A
This is fine the first time I read the example file into a dictionary, but once i save the dictionay into a new file and try to open this file i get the output:
1:"date":12/12/2011, "life":12, "name":A
Is there an easy way to format the data in the dictionary before it is written to file?
Thanks for any advice given
def loadProduct(fileName):
global cheeseDictionary
f = open(fileName,"r")
line = f.readline() # Reads line from file
while line:
line = line[:-1]
data = split(line,":") # Splits line when there is a colon
cheeseDictionary[data[0]] = {"date":data[1], "life":data[2], "name":data[3]} # Stores each split item
line = f.readline() # Next line
f.close()
print cheeseDictionary
def saveProduct(fileName):
global cheeseDictionary
f = open(fileName,"w")
pickle.dump(cheeseDictionary, f)
f.close()
Since you have a specific format you want, you're going to need to write code to emit that format. (I don't know what you're trying to do with pickle in there, that produces a binary format that doesn't bear any resemblance to what you say you're getting.)
For instance, you could redefine saveProduct like so:
def saveProduct(fileName, cheeseDictionary):
f = open(fileName, "w")
for i in sorted(cheeseDictionary.keys()):
v = cheeseDictionary[i]
f.write("%s:%s:%s:%s\n" % (i, v["date"], v["life"], v["name"]))