Remove \r character from the middle of file name - python

I have files on the linux server and their file names are broken because of the middle \r character. I couldn't download those files by using WinScp or Filezilla on windows.
Moreover I couldn't rename or process them properly in python.
On command
files = os.listdir("2014/")
I got this list set.
['16963_6_iris2570_20150110_052515\r_172518.gpx', '29174_3_Sunnam0223_20150114_0 10833\r_130835.gpx', '35767_3_samsi2_20150117_035045\r_155047.gpx', '36581_4_kix ing_20150117_045424\r_165425.gpx', '33383_4_rnrghk10kr_20150117_101618\r_101619. gpx']
On command:
file1 = files[0]
output: _172518.gpxs2570_20150110_052515
Then I try to replace \r
file2 = files[0].replace('\r', '')
output: 16963_6_iris2570_20150110_052515_172518.gpx
That's good but when I try to rename:
os.rename("2014/"+file1, "2014/"+file2)
f = open(file2, "r")
data = f.readlines()
f.close()
output:
Traceback (most recent call last):
File "test.py", line 25, in <module>
f = open(file2, "r")
IOError: [Errno 2] No such file or directory: '29174_3_Sunnam0223_20150114_010833_130835.gpx'

Did you try:
f = open("2014/"+file2, "r")
In your example code above, you included the 2014 folder name in your rename, but not in your open call.

Related

File Opening - Script still finds file in cwd even when absolute path specified

I have looked at How to open a list of files in Python This problem similar but not covered.
path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []
for f in files:
fileNames.append(f)
for fileName in fileNames:
pathFileName = path + fileName
print(f"This is the path: {pathFileName}")
fin = open(pathFileName, 'rt')
texts = []
with open(fileName) as file_in:
# read file text lines into an array
for text in file_in:
texts.append(text)
for text in texts:
print(text)
The file aaaatest.txt is in C:\test\test5 The output is:
This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'
So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:
This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'
The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again.
Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?

Download images from url that is stored in .txt file?

I'm using python 3.6 on Windows 10, I want to download images so that their urls are stored in 1.txt file.
This is my code:
import requests
import shutil
file_image_url = open("test.txt","r")
while True:
image_url = file_image_url.readline()
filename = image_url.split("/")[-1]
r = requests.get(image_url, stream = True)
r.raw.decode_content = True
with open(filename,'wb') as f:
shutil.copyfileobj(r.raw, f)
but when I run the code above it gives me this error:
Traceback (most recent call last):
File "download_pictures.py", line 10, in <module>
with open(filename,'wb') as f:
OSError: [Errno 22] Invalid argument: '03.jpg\n'
test.txt contains:
https://mysite/images/03.jpg
https://mysite/images/26.jpg
https://mysite/images/34.jpg
When I tried to put just one single URL on test.txt, it works and downloaded the picture,
but I need to download several images.
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.
You are passing this filename(with \n) to open function(hence the OSError). So you need to call strip() on filename before passing into open.
Your filename has the new line character (\n) in it, remove that when you’re parsing for the filename and it should fix your issue. It’s working when you only have one file path in the txt file because there is only one line.

Direction in ubuntu

Trying to run bot in server. Ubuntu 20.1
Line in code(Python3)
...
for elem in items['stats']:
f = open(r"\root\bot_python\list.txt", "r+")
...
Traceback
Traceback (most recent call last):
File "bot_last_final_18_01_2021.py", line 57, in <module>
f = open(r"\root\bot_python\list.txt", "r+")
FileNotFoundError: [Errno 2] No such file or directory: '\\root\\bot_python\\list.txt'
How correctly write directoty?
Directory paths in Linux use forward slash, so try:
for elem in items['stats']:
f = open("/root/bot_python/list.txt", "r+")
On linux you use "/" instead of "\". So the file location would be /root/bot_python/list.txt.
If that doesn't work then try without the .txt at the end. That should be it

FileNotFoundError in opening txt file with python

I am trying to open a txt file for reading with this code:-
type_comments = [] #Declare an empty list
with open ('society6comments.txt', 'rt') as in_file: #Open file for reading of text data.
for line in in_file: #For each line of text store in a string variable named "line", and
type_comments.append(line.rstrip('\n')) #add that line to our list of lines.
Error:-
Error - Traceback (most recent call last):
File "c:/Users/sultan/python/society6/society6_promotion.py", line 6, in <module>
with open ('society6comments.txt', 'rt') as in_file:
FileNotFoundError: [Errno 2] No such file or directory: 'society6comments.txt'
I already have a file name with 'society6comments.txt' in the same directory has my script so why is it showing error?
The fact that the text file is in the same directory as your program does not make that directory the current working directory. Put the full path to the file in your open() call.
You can use os.path.dirname(__file__) to obtain the directory name of the script, and then join the file name you want:
import os
with open (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'society6comments.txt'), 'rt') as in_file:

reading logfile and opening files in there

I'm having a problem reading a logfile I'm creating in another method.
The logfile has file-paths of unzipped files in it (unpacking is in another function). The logfile looks kinda like this
/home/usr/Downloads/outdir/Code/XXX.something
/home/usr/Downloads/outdir/Code/YYY.something
/home/usr/Downloads/outdir/Code/AAA.something
#staticmethod
def iterate_log(path):
results = str()
for dirpath, dirnames, files in os.walk(path):
for name in files:
results += '%s\n' % os.path.join(dirpath, name)
with open(os.path.join(EXTRACT_PATH_, LOGNAME_), 'w') as logfile:
logfile.write(results)
return os.path.join(EXTRACT_PATH_, LOGNAME_)
#staticmethod
def read_received_files(from_file):
with open(from_file, 'r') as data:
data = data.readlines()
for lines in data:
# to reduce confusion I would use
# for line in data:
read_files = open(lines)
print(read_files)
return read_files
Now I want to read the logfile line by line (the parameter from_files in the second method is the return value of the first method right now) and open those files and return them (for using them elsewhere).
readlines() and read() are both giving me errors so far
readlines() = [Errno2] No sucht file or directory: '/../../../logfile.log\n
read() = IsADirectoryError: [Errno21]
whole traceback:
Traceback (most recent call last):
File "files_received_test.py", line 13, in <module>
main()
File "files_received_test.py", line 9, in main
j = Filesystem.execute_code(FILENAME_)
File "/home/usr/PycharmProjects/Projektgruppe/code/src/filesystem_hasher.py", line 16, in execute_code
Filesystem.read_received_files(create_log)
File "/home/usr/PycharmProjects/Projektgruppe/code/src/filesystem_hasher.py", line 54, in read_received_files
read_files = open(lines)
FileNotFoundError: [Errno 2] No such file or directory: '/home/usr/Downloads/outdir/unpacked_files.log\n'
You just need to strip the newline character so change
read_files = open(lines)
to
read_files = open(lines.strip())
as an observation - critical to read each character in an error message - the message was telling you that there was no file named
'/home/usr/Downloads/outdir/unpacked_files.log\n'
so it is useful to then try to understand why the \n showed up - this did not match your expectation of the file name so you should wonder why the file has that name

Categories

Resources