how to import .txt with space in filename - python-3.x

Code:
import sys
with open(sys.argv[1]) as f:
lines = f.readlines()
for line in lines[0:]:
columns = line.split()
print(columns[0])
Output:
Traceback (most recent call last):
File "scissors.py", line 2, in <module>
with open (sys.argv[1]) as f:
FileNotFoundError: [Errno 2] No such file or directory: '1'
(Links to old images: https://i.stack.imgur.com/aG1vr.png, https://i.stack.imgur.com/wSpLG.png)

Wrap the file name in quotation marks like this "your file.txt"
If you have a filepath, use the raw string (and backslashes in the copied filepath) by placing a r before the quotation marks:
r"C:\Folder\Subfolder\another_one\your_file.txt"

Related

Having problems with python putting 2 backslashes in path

I have this problem that python puts 2 backlashes in an path and I don't understand why.
Here is the code:
with open(os.path.join("Users", "Kasutaja", "AppData", "Local", "Growtopia", "save.dat"), 'r+') as f:
file_data = f.read()
It gives me this=
C:\Users\Kasutaja\AppData\Local\Programs\Python\Python39\python.exe "C:/Users/Kasutaja/Desktop/Growtopia Hack.py"
Game not found! Make sure to open this before Growtopia
Traceback (most recent call last):
File "C:\Users\Kasutaja\Desktop\Growtopia Hack.py", line 61, in <module>
with open(os.path.join("Users", "Kasutaja", "AppData", "Local", "Growtopia", "save.dat"), 'r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Kasutaja\\AppData\\Local\\Growtopia\\save.dat'
Process finished with exit code 1

Error when trying to create a file in a path containing parentheses with Python

Can anyone spot why this is failing?
import pathlib
from shlex import quote
path = 'testdir(abc)/subdir(123)'
filename = 'test'
content = \
"""hello
world
"""
pathlib.Path(path).mkdir(mode=0o770, parents=True, exist_ok=True)
md5_filename = quote(str(pathlib.Path(path) / (filename + '.txt')))
with open(md5_filename, 'w') as f:
f.write(content)
I'm getting this traceback
(tools) $ python test_filemake.py
Traceback (most recent call last):
File "test_filemake.py", line 13, in <module>
with open(md5_filename, 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: "'testdir(abc)/subdir(123)/test.txt'"
I think I don't understand posix paths well enough to understand what's going on. If I take the parentheses out of the directory names in the path, it works fine. shlex.quote() is adding the extra layer of double quotes, which seems to be breaking things.

Python passing a string value from a table to a function

I'm trying to go through a list of items and passing each one to a function one by one to create an Excel file with the same name as the argument passed. I am getting the error below which I believe is related to the '/' in the String name. Can anyone advise how I get it to ignore this?
>>> test.createExcel(filename)
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
test.createExcel(filename)
File "C:\Users\danie\OneDrive\JVC\project1.py", line 52, in createExcel
wb2.save(modelname+'.xlsx')
File "C:\Users\danie\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 392, in save
save_workbook(self, filename)
File "C:\Users\danie\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Users\danie\AppData\Local\Programs\Python\Python37\lib\zipfile.py", line 1240, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: '14 A4/32GB BLU.xlsx'
A filename cannot contain any of the following characters: \ / : * ? " < > |
In ur caseļ¼Œ u could replace ur filename using str.replace('/','-') or any other character u'd like to.
eg:
wb.save(filename.replace('\','-'))
Or using the regular expression to replace it may work well.

Os walk directory return string literal for unzipping

The problem occurs where the string variable tries to get read by zipfile.Zipfile(variable). The callback is file does not exist. This is because it is adding an extra \ to each folder. I tried several things to try and make the string into a literal but when I do this it prints an extra \\\. I tried even making that a literal but as I would expect it repeated the same thing returning \\\\\.Any insight would be greatly appreciated!!!
The code structure is below and here are the callback functions
Traceback (most recent call last):
File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module>
z = zipfile.ZipFile(zf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: "C:\\Users\\Yume\\AppData\\Roaming\\
Traceback (most recent call last):
File "C:\Users\Yume\Desktop\Walk a Dir Unzip and copy to.py", line 17, in <module> z = zipfile.ZipFile(rzf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '"C:\\\\Users\\\\Yume\\\\AppData\\\\Roaming\\\\
z = zipfile.ZipFile(rrzf, 'r')
File "C:\Users\Yume\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__
self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: '\'"C:\\\\\\\\Users\\\\\\\\Yume\\\\\\\\AppData\\\\\\\\Roaming\\\\\\\
CODE:
import os
import re
from shutil import copyfile
import zipfile
import rarfile
isRar = re.compile('.+\\.rar')
isZip = re.compile('.+\\.zip')
for folderName, subfolders, filenames in os.walk(r'C:\Users\Yume\AppData'):
if isZip.match(str(filenames)):
zf = folderName+ str(subfolders)+str(filenames)
rzf = '%r'%zf
z = zipfile.ZipFile(zf)
z.extractall(r'C:\Users\Yume')
z.close()
if isRar.match(str(filenames)):
rf = folderName+ str(subfolders)+str(filenames)
rrf = "%r"%rf
r = rarfile.RarFile(rf)
r.extractall(r'C:\Users\Yume')
r.close()
My problem was corrected by running a for loop through the file list created by os walk. I cleaned up my code and here is a working program that walks a directory find a compressed .zip or .rar and extracts it to the specified destination.
import os
import zipfile
import rarfile
import unrar
isRar = re.compile('.*\\.rar')
isZip = re.compile('.*\\.zip')
for dirpath, dirnames, filenames in os.walk(r'C:\Users\'):
for file in filenames:
if isZip.match(file):
zf = os.path.join(dirpath, file)
z= zipfile.ZipFile(zf)
z.extractall(r'C:\Users\Unzipped')
z.close()
if isRar.match(file):
rf = os.path.join(dirpath, file)
r = rarfile.RarFile(rf)
r.extractall(r'C:\Users\Unzipped')
r.close()

python3 shutil error copying from config list

Im trying to copy a file using shutil by reading in a config.dat file.
This file is simply:
/home/admin/Documents/file1
/home/admin/Documents/file2
Code does work but it will copy file1 okay but then misses file2 because it see a \n there, which im guessing is because of the new line.
#!/usr/bin/python3
import shutil
data = open("config.dat")
filelist = data.read()
src = filelist
dest = '/home/admin/Documents/backup/'
shutil.copy(src, dest)
Error code im getting :
Traceback (most recent call last):
File "./testing.py", line 18, in <module>
shutil.copy(src, dest)
File "/usr/lib/python3.4/shutil.py", line 229, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.4/shutil.py", line 108, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory:
'/home/admin/Documents/file1\n/home/admin/Documents/file2'
I would like the copy of those files to run based on the files from the config.dat folder but it detects a '\n'. Is there a way to fix this?
thanks for the help
Use split('\n') to get a list of files and the iterate that list. You probably want to throw in the file.strip() to get rid of trailing whitespace and empty lines.
import shutil
dest = '/home/admin/Documents/backup/'
with open('config.dat') as data:
filelist = data.read().split('\n')
for file in filelist:
if file:
shutil.copy(file.strip(), dest)
Or, if you don't need the filelist after this
with open('config.dat') as data:
for file in data:
if file:
shutil.copy(file.strip(), dest)

Resources