P4 Python error: file(s) not on client - python

I am using the p4 Python module to try and open several files for edit. Basically I have a list of files that I am grabbing from a txt document. I then do some formatting to each item in the list and append those items to an empty list. My method is not the most efficient but I am just trying to get this to work before optimizing.
edit_files = []
with open('C:\\Users\\rgriffin\Desktop\\replace.txt', 'r' )as f:
for line in f:
l = line.partition(',')[0]
e = l.replace('#(', '')
r = e.replace('U:\\', '//Stream/main/')
q= r.replace('\\', '/')
edit_files.append(q)
f.close
for i in edit_files:
p4.run("edit" , i)
With this code I get an error:
[Warning]: '"//Stream/main/Data/anims/stuff/char/Emotion_Angry.hkx" - file(s) not on client.'
If I change the last line to this...
p4.run("edit" , "//Stream/main/Data/anims/stuff/char/Emotion_Angry.hkx")
The file is checked out as expected. I did a type check and i is a string.
Input data:
#("U:\Data\anims\stuff\char\Emotion_Angry_Partial.hkx", "u:\Assets\Actors\stuff\char\Animation\char_Idle.max")

In the following command, there are quote characters at ends. Do remove them. Also seems like there are empty lines.
Change
for i in edit_files:
p4.run("edit" , i)
to
for i in edit_files:
f=i.replace('"','').strip()
if len(f)>0:
print "Opening ["+f+"]"
p4.run("edit" , f)
or One liner
[p4.run("edit" , i.replace('"','').strip()) for i in edit_files if i.strip()]
Or you may want to change your populating code itself:
Use:
with open('C:\\Users\\rgriffin\Desktop\\replace.txt', 'r' )as f:
for line in f:
l = line.partition(',')[0].replace('#(', '').replace('U:\\', '//Stream/main/').replace('\\', '/').replace('"', '').strip()
if len(l)>0:
edit_files.append(l)
f.close

Related

Python list iterate not working as expected

I have a file called list.txt:
['d1','d2','d3']
I want to loop through all the items in the list. Here is the code:
deviceList = open("list.txt", "r")
deviceList = deviceList.read()
for i in deviceList:
print(i)
Here the issue is that, when I run the code, it will split all the characters:
% python3 run.py
[
'
d
1
'
,
'
d
2
'
,
'
d
3
'
]
It's like all the items have been considered as 1 string? I think needs to be parsed? Please let me know what am I missing..
Simply because you do not have a list, you are reading a pure text...
I suggest writing the list without the [] so you can use the split() function.
Write the file like this: d1;d2;d3
and use this script to obtain a list
f = open("filename", 'r')
line = f.readlines()
f.close()
list = line.split(";")
if you need the [] in the file, simply add a strip() function like this
f = open("filename", 'r')
line = f.readlines()
f.close()
strip = line.strip("[]")
list = strip.split(";")
should work the same
This isn't the cleanest solution, but it will do if your .txt file is always just in the "[x,y,z]" format.
deviceList = open("list.txt", "r")
deviceList = deviceList[1:-1]
deviceList = deviceList.split(",")
for i in deviceList:
print(i)
This takes your string, strips the "[" and "]", and then separates the entire string between the commas and turns that into a list. As other users have suggested, there are probably better ways to store this list than a text file as it is, but this solution will do exactly what you are asking. Hope this helps!

list index out of range python txt

I have txt file which looks like:
New York,cinema,3,02/04/2022
But I've got error in list, even if this code works to another txt files without date, what's the problem?
def finished_objects():
file = open("finished_objects.txt", "r",encoding="UTF8")
lines = file.readlines()
L = [] # assign empty list with name 'L'
for line in lines:
L.append(line.replace("\n", "").split(","))
file.close()
for i in range(len(L)):
print(L[i][0], ":", L[i][1], ". Quantity:", L[i][2], ". Date: ", L[i][3])
return L
You can also use "with" for opening files like,
with open("finished_objects.txt", "r",encoding="UTF8") as file:
lines = file.readlines()
L = [] # assign empty list with name 'L'
for line in lines:
L.append(line.replace("\n", "").split(","))
# rest of your code
That way you don't have to manage the connection.
Works fine on my end. Might be that your file has one entry with less commas than others. You could do a simple if len(L) != 4 inside your last loop to make sure you won't get errors while running.

how to append two files within the same script after if loop statements OR how to append directly to text file. Python

I have a script that I've been working on turning four individual steps(scripts) into 1. I'm down to my last problem and I know I'm over thinking it but need a bit of help to turn the corner.
I either need to figure out how to merge two files after the last IF-LOOP Statement or find some way to write directly to one text file from the script in the order needed (listed below as final).
Currently, the script shows I'm trying to merge(append) at the bottom after the IF-LOOP statements. If a more efficient way is better please shine some light for me. Just to be more clear hopefully, I have tried to write directly to one file and both if-Statement matches show up but my second da_list header repeats because it's inside the loop or doesn't show at all if I have the text header outside the loop. That's why you see the headers appearing before the if statements. Also, just so you know what the cf.txt file look like.
cf.txt example piece. Dots (periods) are one per column (A-D). Mixchar words start in column E
ABCDE
header row
. . . . 5J1SYMC2
. . . . 2TEHUOB1
. . . . TWSIHNB2
. . . . SYHNRWE2
. . . . BFHYSJF1
cf = open(r"E:\test2\cf.txt", "r")
f = open(r"E:\test2\F.txt", "r")
da = open(r"E:\test2\DA.txt","r")
output5 = open(r"E:\test2\output5.txt", "a")
output6 = open(r"E:\test2\output6.txt", "a")
list2 = f.read().split()
list3 = da.read().split()
next(cf)
newlist = []
f_list = []
da_list = []
output5.write(" F_List \n") #text header for output5
output5.write("\n")
output6.write(" Da_List \n") #text header for output6
output6.write("\n")
for line in cf: #cycles thru cf.txt column 5 removes last 2 chars_
rc = (line.split()[4][:-2]) #and append string(rc) in (newlist).
if rc not in newlist:
newlist = []
newlist.append(rc)
check = any(item in newlist for item in list2) #check string(rc) if exist in f_list_
if check is True: #clears previous f_list line and appends new.
if rc not in f_list:
f_list = []
f_list.append(f'{rc}', ),
output5.write(f'{f_list}'[2:-2]), #writes (rc) strings that exist in f_list to
output5.write('\n') #output5.txt
check = any(item in newlist for item in list3) #check string(rc) if exist in da_list_
if check is True: #clears previous da_list line and appends new.
if rc not in da_list:
da_list = []
da_list.append(f'{rc}', ),
output6.write(f'{da_list}'[2:-2]), #writes (rc) strings that exist in f_list to
output6.write('\n') #output6.txt
fin = open(r"E:\test2\output6.txt", "r") #trying to append output6.txt to output5.txt
data2 = fin.read()
fin.close()
fout = open(r"E:\test2\output5.txt", "a")
fout.write(data2)
fout.close()
Final result wanted in output5.txt file. F_list header with random mixchar words matches from (cf.txt) string and f_list. And the same for the da_list printed(appended) below.
F_List
2TEHUO
5JESYM
BFHYSJ
SYHNRW
TWSIHN
Da_List
HKHDU7
DJSKUO
DJDH8
KSIE3
SWSYR
One solution could be to just append the file to the second file. You should consider using variables for the file paths instead of copy-paste. Also, the name of the files is a bit confusing.
output5.close()
output6.close()
with open(r"E:\test2\output5.txt", 'a') as output5:
with open(r"E:\test2\output6.txt", "r") as output6:
output5.write(output6.read())
Relevant question about appending files
Here is a explanation of how you can use the with statement
Also, instead of writing the content directly to the files in the if statement, why not just store it into strings? Then in the end you could write it to a file.
If you try to read from a file, before closing it, the text won't show up. You can try the snippet below.
output5 = open(r"Test", "w")
output5.write("Foo")
output6 = open(r"Test", "r")
print(output6.read())

Avoid newline in python output

Code snippet below compares two csv files and merge them. My problem is that the second file is printed in new lines.
import csv
import dateutil.parser
with open('a.csv', 'r') as f1:
feed = f1.readlines()
with open ('b.csv', 'r') as f2:
for line in f2.readlines()[1:]:
line = line.split(',')
ts = dateutil.parser.parse(line[3])
print(ts)
for i, log in enumerate(feed):
ls = log.split(',')
ts_start = dateutil.parser.parse(ls[0])
ts_end = dateutil.parser.parse(ls[1])
if (ts >= ts_start) and (ts < ts_end):
print(ts, ts_start, ts_end)
name, tags, mean = line[0], ','.join(line[1:3]),line[-1]
feed[i] = ','.join([log, name, tags, mean])
with open('c.csv', 'w') as f:
f.writelines(feed)
file a:
2015-11-04T13:35:18.657Z,2015-11-04T13:47:06.588Z,load,INSERT
2015-11-04T13:47:47.164Z,2015-11-04T14:07:13.230Z,run,READUPDATE
file b:
name,tags,time,mean
memory_value,"type=memory,instance=buffered",2015-11-04T13:35:00Z,
memory_value,"type=memory,instance=buffered",2015-11-04T13:45:00Z,1.32
memory_value,"type=memory,instance=buffered",2015-11-04T14:05:00Z,1.11
Output:
A1,A2,A3,A4,
A5
B1,B2,B3,B4,
B5,
Expected output:
A1,A2,A3,A4,A5
B1,B2,B3,B4,B5
How can I acheive this?
Thanks
The strings in the list returned by readlines include the newline character at the end of each line, so these may inadvertently be included as you do string manipulation on that data. In particular, ','.join([log, name, tags, mean]) will have a newline between log and name, because log ultimately came from f1.readlines().
Try stripping the newlines from each line before doing anything with it.
for i, log in enumerate(feed):
log = log.strip()
ls = log.split(',')
It may also be necessary to do line = line.strip().split(',') at the top of the first for loop instead of just line = line.split(','). The output looks OK on my machine without it, but I'm not 100% sure that it exactly matches your desired output.
Depending on what version of python you are using you may need to change the 'r' and 'w' to 'rb' and 'wb' in order to read and write files in binary mode. This should help with the new lines.

Parsing the text in a file

I am trying print the contents of a text file using below code,the text file will only contain one line,my current output is as below which
is a list with "\r\n" at the end,I want to the output to be as shown in "EXPECTED OUTPUT" ?
branch_textfile = branch + '.txt'
with open(branch_textfile, 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
#contents = contents.rstrip()
print contents
CURRENT OUTPUT:-
['AU_TEST_PUBLIC_BRANCH.05.01.01.151.005\r\n']
EXPECTED OUTPUT:-
AU_TEST_PUBLIC_BRANCH.05.01.01.151.005
>>> x = ['AU_TEST_PUBLIC_BRANCH.05.01.01.151.005\r\n']
>>> print x[0].rstrip()
AU_TEST_PUBLIC_BRANCH.05.01.01.151.005
>>>
It does that because f.readlines() returns an array (or is it a list?) Either way, you can avoid the brackets with:
print contents[0]
This works but it only prints the first line of the file.
Use contents = f.read().rstrip() instead of contents = f.readlines(). This will read the file into a single string and remove the trailing whitespace.
why did you "#" the .rstrip() out? it is the right command!
you can also put that on the end of the statment like this:
with open('file','r') as f:
data = f.read().strip()

Categories